将图像转换为字节数组

11

请问有人能告诉我如何将图像(.jpg, .gif, .bmp)转换成字节数组吗?


你的图片在哪里?在文件中还是在图像对象或某个流中? - Albin Sunnanbo
使用 OpenFileDialog 将图像上传到 PictureBox。 - Riya
你为什么需要将图像转换成字节数组?是为了存储吗?还是想要对图像进行操作? - yhw42
6个回答

12

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

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

6
如果您的图像已经是一个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(); 
     }
}

您可以像这样在图片框控件中使用此函数:
byte[] imageBytes = convertImageToByteArray(pictureBox1.Image);

@riya7887:请使用我上面编辑过的版本,因为它可以正确释放流。 - MusiGenesis

6

我假设您想要的是像素值。假设 bitmap 是一个 System.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);

请注意,'stride'是每一行像素数据所需的字节数。这里有更多的解释(点击此处)

2
为什么要踩这个问题?这个问题可以理解为“我想把图像像素值作为字节数组”或“我想把图像文件作为字节数组”,不是吗? - Cocowalla
您的回答最初没有第三行,而您的第一行让我感到困惑,直到我喝了咖啡。请编辑它,我会取消我的投票。 - MusiGenesis
公正的观点,谢谢您的解释 :) 我已经添加了一个简短的注释,说明步幅是什么。 - Cocowalla
其实,你确定你的步长计算是正确的吗?步长需要是32位对齐的,但我认为你的代码只能将其8位对齐。 - MusiGenesis
你的步幅计算适用于任何32位每像素格式,因为它已经是32位对齐的。幸运的是,在.Net中默认的Bitmap是ARGB8888。 - MusiGenesis
显示剩余2条评论

0

获取任何文件的字节,请尝试:

byte[] bytes =  File.ReadAllBytes(pathToFile);

0

基于MusiGenesis; 对我帮助很大,但我有许多图像类型。这将保存它可以读取的任何图像类型。

            System.Drawing.Imaging.ImageFormat ImageFormat = imageToConvert.RawFormat;
        byte[] Ret;
        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageToConvert.Save(ms, ImageFormat);
                Ret = ms.ToArray();
            }
        }
        catch (Exception) { throw; }
        return Ret;

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接