如何将图像转换为字节数组

Sha*_*ank 99 c# wpf

任何人都可以建议我如何将图像转换为字节数组,反之亦然?

如果有人有一些代码样本来帮助我,那就太好了.

我正在开发一个WPF应用程序并使用流阅读器.

Pra*_*ana 135

用于将图像更改为字节数组的示例代码

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
   using (var ms = new MemoryStream())
   {
      imageIn.Save(ms,imageIn.RawFormat);
      return  ms.ToArray();
   }
}
Run Code Online (Sandbox Code Playgroud)

C#图像到字节数组和字节数组到图像转换器类

  • 而不是`System.Drawing.Imaging.ImageFormat.Gif`,你可以使用`imageIn.RawFormat` (12认同)

AR5*_*HAM 48

对于转换Image对象,byte[]您可以执行以下操作:

public static byte[] converterDemo(Image x)
{
    ImageConverter _imageConverter = new ImageConverter();
    byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));
    return xByte;
}
Run Code Online (Sandbox Code Playgroud)

  • 完美答案!....无需定义"图像文件扩展名",正是我所寻找的. (4认同)
  • 附带说明:这可能包含您不希望拥有的其他元数据;-) 要摆脱元数据,您可能需要创建一个 _new Bitmap_ 并将 _Image_ 传递给它,例如 `.ConvertTo(new Bitmap(x ), typeof(byte[]));`。 (2认同)
  • 那么,嗯,这实际上将图像转换成什么呢?这些字节里面有什么? (2认同)

Nee*_*lam 30

从图像路径获取字节数组的另一种方法是

byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));
Run Code Online (Sandbox Code Playgroud)

  • 他们的问题被标记为 WPF(因此没有理由认为它在服务器中运行并包含 MapPath)并且显示他们已经拥有该图像(没有理由从磁盘读取它,甚至不假设它一开始就在磁盘上)。抱歉,您的回复似乎与问题完全无关 (3认同)

ani*_*key 16

试试这个:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}
Run Code Online (Sandbox Code Playgroud)


She*_*har 14

您可以使用File.ReadAllBytes()方法将任何文件读入字节数组.要将字节数组写入文件,只需使用File.WriteAllBytes()方法.

希望这可以帮助.

您可以在此处找到更多信息和示例代码.

  • 或许。我十年前写了这个答案,当时我还是个菜鸟。 (3认同)

Ren*_*Pet 14

这是我目前正在使用的.我尝试过的其他一些技术并非非最佳,因为它们改变了像素的位深度(24位与32位)或忽略了图像的分辨率(dpi).

  // ImageConverter object used to convert byte arrays containing JPEG or PNG file images into 
  //  Bitmap objects. This is static and only gets instantiated once.
  private static readonly ImageConverter _imageConverter = new ImageConverter();
Run Code Online (Sandbox Code Playgroud)

图像到字节数组:

  /// <summary>
  /// Method to "convert" an Image object into a byte array, formatted in PNG file format, which 
  /// provides lossless compression. This can be used together with the GetImageFromByteArray() 
  /// method to provide a kind of serialization / deserialization. 
  /// </summary>
  /// <param name="theImage">Image object, must be convertable to PNG format</param>
  /// <returns>byte array image of a PNG file containing the image</returns>
  public static byte[] CopyImageToByteArray(Image theImage)
  {
     using (MemoryStream memoryStream = new MemoryStream())
     {
        theImage.Save(memoryStream, ImageFormat.Png);
        return memoryStream.ToArray();
     }
  }
Run Code Online (Sandbox Code Playgroud)

字节数组到图像:

  /// <summary>
  /// Method that uses the ImageConverter object in .Net Framework to convert a byte array, 
  /// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be 
  /// used as an Image object.
  /// </summary>
  /// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
  /// <returns>Bitmap object if it works, else exception is thrown</returns>
  public static Bitmap GetImageFromByteArray(byte[] byteArray)
  {
     Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);

     if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
                        bm.VerticalResolution != (int)bm.VerticalResolution))
     {
        // Correct a strange glitch that has been observed in the test program when converting 
        //  from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts" 
        //  slightly away from the nominal integer value
        bm.SetResolution((int)(bm.HorizontalResolution + 0.5f), 
                         (int)(bm.VerticalResolution + 0.5f));
     }

     return bm;
  }
Run Code Online (Sandbox Code Playgroud)

编辑:要从jpg或png文件获取图像,您应该使用File.ReadAllBytes()将文件读入字节数组:

 Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
Run Code Online (Sandbox Code Playgroud)

这避免了与Bitmap相关的问题,希望其源流保持打开状态,并且一些建议的解决方法是导致源文件保持锁定的问题.


Las*_*olt 5

您是否只想将像素或整个图像(包括标题)作为字节数组?

对于像素:使用CopyPixels位图上的方法.就像是:

var bitmap = new BitmapImage(uri);

//Pixel array
byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc.

bitmap.CopyPixels(..size, pixels, fullStride, 0); 
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您不引用 imageBytes 以在流中携带字节,则该方法将不会返回任何内容。确保您引用 imageBytes = m.ToArray();

    public static byte[] SerializeImage() {
        MemoryStream m;
        string PicPath = pathToImage";

        byte[] imageBytes;
        using (Image image = Image.FromFile(PicPath)) {
            
            using ( m = new MemoryStream()) {

                image.Save(m, image.RawFormat);
                imageBytes = new byte[m.Length];
               //Very Important    
               imageBytes = m.ToArray();
                
            }//end using
        }//end using

        return imageBytes;
    }//SerializeImage
Run Code Online (Sandbox Code Playgroud)