且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将位图转换成字节数组

更新时间:2023-11-09 13:40:16

有几种方法。

ImageConverter

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

这一个是方便,因为它不需要大量的code的。

This one is convenient because it doesn't require a lot of code.

内存流

public static byte[] ImageToByte2(Image img)
{
    byte[] byteArray = new byte[0];
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();

        byteArray = stream.ToArray();
    }
    return byteArray;
}

这一个是等同于你在做什么,除了文件被保存到内存,而不是磁盘。虽然越来越多的code你的imageformat的选择,它可以保存到内存或磁盘之间方便地进行修改。

This one is equivalent to what you are doing, except the file is saved to memory instead of to disk. Although more code you have the option of ImageFormat and it can be easily modified between saving to memory or disk.

来源: http://www.vcskicks.com/image-to-byte.php