// バイト配列をImageオブジェクトに変換
public static Image ByteArrayToImage(byte[] b) {
ImageConverter imgconv = new ImageConverter();
Image img = (Image)imgconv.ConvertFrom(b);
return img;
}
// Imageオブジェクトをバイト配列に変換
public static byte[] ImageToByteArray(Image img) {
ImageConverter imgconv = new ImageConverter();
byte[] b = (byte[])imgconv.ConvertTo(img, typeof(byte[]));
return b;
}
' バイト配列をImageオブジェクトに変換
Public Shared Function ByteArrayToImage(ByVal b As Byte()) As Image
Dim imgconv As New ImageConverter()
Dim img As Image = CType(imgconv.ConvertFrom(b), Image)
Return img
End Function
' Imageオブジェクトをバイト配列に変換
Public Shared Function ImageToByteArray(ByVal img As Image) As Byte()
Dim imgconv As New ImageConverter()
Dim b As Byte() = _
CType(imgconv.ConvertTo(img, GetType(Byte())), Byte())
Return b
End Function
Imports System
Imports System.Net
Imports System.IO
Imports System.Drawing
Class ByteArrayAndImage
Shared imgconv As New ImageConverter()
' バイト配列をImageオブジェクトに変換
Public Shared Function ByteArrayToImage(ByVal b As Byte()) As Image
Dim img As Image = CType(imgconv.ConvertFrom(b), Image)
Return img
End Function
' Imageオブジェクトをバイト配列に変換
Public Shared Function ImageToByteArray(ByVal img As Image) As Byte()
Dim b As Byte() = _
CType(imgconv.ConvertTo(img, GetType(Byte())), Byte())
Return b
End Function
Shared Sub main()
' 画像のURL
Dim url As String = "http://www.atmarkit.co.jp" _
+ "/fdotnet/dotnettips/index/dotnettips_m.jpg"
' 画像をバイト配列としてダウンロード
Dim wc As New WebClient()
Dim jpgBytes As Byte() = wc.DownloadData(url)
wc.Dispose()
' Byte() → Image
Dim img As Image = ByteArrayToImage(jpgBytes)
' Image → Byte()
Dim b As Byte() = ImageToByteArray(img)
' 再度、Byte() → Image
Dim img2 As Image = ByteArrayToImage(b)