How to convert image to byte array

前端 未结 12 1409
悲哀的现实
悲哀的现实 2020-11-22 09:52

Can anybody suggest how I can convert an image to a byte array and vice versa?

I\'m developing a WPF application and using a stream reader.

相关标签:
12条回答
  • 2020-11-22 10:21

    Sample code to change an image into a byte array

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

    C# Image to Byte Array and Byte Array to Image Converter Class

    0 讨论(0)
  • 2020-11-22 10:24

    Here's what I'm currently using. Some of the other techniques I've tried have been non-optimal because they changed the bit depth of the pixels (24-bit vs. 32-bit) or ignored the image's resolution (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();
    

    Image to byte array:

      /// <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();
         }
      }
    

    Byte array to Image:

      /// <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;
      }
    

    Edit: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():

     Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
    

    This avoids problems related to Bitmap wanting its source stream to be kept open, and some suggested workarounds to that problem that result in the source file being kept locked.

    0 讨论(0)
  • 2020-11-22 10:29

    Another way to get Byte array from image path is

    byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));
    
    0 讨论(0)
  • 2020-11-22 10:29

    Do you only want the pixels or the whole image (including headers) as an byte array?

    For pixels: Use the CopyPixels method on Bitmap. Something like:

    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); 
    
    0 讨论(0)
  • 2020-11-22 10:33

    This is Code for converting the image of any type(for example PNG, JPG, JPEG) to byte array

       public static byte[] imageConversion(string imageName){            
    
    
            //Initialize a file stream to read the image file
            FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);
    
            //Initialize a byte array with size of stream
            byte[] imgByteArr = new byte[fs.Length];
    
            //Read data from the file stream and put into the byte array
            fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
    
            //Close a file stream
            fs.Close();
    
            return imageByteArr
        }
    
    0 讨论(0)
  • 2020-11-22 10:39

    For Converting an Image object to byte[] you can do as follows:

    public static byte[] converterDemo(Image x)
    {
        ImageConverter _imageConverter = new ImageConverter();
        byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));
        return xByte;
    }
    
    0 讨论(0)
提交回复
热议问题