将图像转换为字节数组

Riy*_*iya 11 .net c#

任何人都可以告诉我如何将图像(.jpg,.gif,.bmp)转换为字节数组?

san*_*ngh 12

将图像转换为字节的最简单方法是使用System.Drawing命名空间下的ImageConverter类

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


Mus*_*sis 6

如果您的图片已经是a的形式System.Drawing.Image,那么您可以执行以下操作:

public byte[] convertImageToByteArray(System.Drawing.Image image)
{
     using (MemoryStream ms = new MemoryStream())
     {
         image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 
             // or whatever output format you like
         return ms.ToArray(); 
     }
}
Run Code Online (Sandbox Code Playgroud)

您可以将此功能与图片框控件中的图像一起使用,如下所示:

byte[] imageBytes = convertImageToByteArray(pictureBox1.Image);
Run Code Online (Sandbox Code Playgroud)


Coc*_*lla 6

我假设你想要的是像素值.假设bitmapSystem.Windows.Media.Imaging.BitmapSource:

int stride = bitmap.PixelWidth * ((bitmap.Format.BitsPerPixel + 7) / 8);
byte[] bmpPixels = new byte[bitmap.PixelHeight * stride];
bitmap.CopyPixels(bmpPixels, stride, 0);
Run Code Online (Sandbox Code Playgroud)

注意,'stride'是每行像素ddata所需的字节数.这里有更多解释.

  • 为什么选择downvote?当然这个问题可以解释为"我希望图像像素值作为字节数组"或"我希望图像文件作为字节数组"? (2认同)