java bitmap转换成byte数组_C#/.NET应用程序编程开发中如何将bitmap转换成字节数组(byte[])?...

问题描述

在C#/.NET应用程序编程开发中,如何将bitmap转换成字节数组(byte[])?

方案一

使用ImageConverter,实现方法如下:

public static byte[] ImageToByte(Image img)

{

ImageConverter converter = new ImageConverter();

return (byte[])converter.ConvertTo(img, typeof(byte[]));

}

方案二

使用MemoryStream,实现方法如下:

public static byte[] ImageToByte2(Image img)

{

using (var stream = new MemoryStream())

{

img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

return stream.ToArray();

}

}

方案三

使用Marshal.Copy()方法,实现方法如下:

public static byte[] BitmapToByteArray(Bitmap bitmap)

{

BitmapData bmpdata = null;

try

{

bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);

int numbytes = bmpdata.Stride * bitmap.Height;

byte[] bytedata = new byte[numbytes];

IntPtr ptr = bmpdata.Scan0;

Marshal.Copy(ptr, bytedata, 0, numbytes);

return bytedata;

}

finally

{

if (bmpdata != null)

bitmap.UnlockBits(bmpdata);

}

}

你可能感兴趣的:(java,bitmap转换成byte数组)