C# byte[]与Bitmap互转

首先先观察一下本地bmp图像结构(参考: https://blog.csdn.net/qq_37872392/article/details/124710600):

C# byte[]与Bitmap互转_第1张图片

 可以看到bmp图像结构除了纯图像像素点位信息,还有一块未用空间(OffSet)。

  • 所以如果需要得到图像所有数据进行转换,则可以使用网上提供的大部分方式:

bitmap转byte[]:

public byte[] BitmapToByte(System.Drawing.Bitmap bitmap)
{
      System.IO.MemoryStream ms = new System.IO.MemoryStream();
      bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
      ms.Seek(0, System.IO.SeekOrigin.Begin);
      byte[] bytes = new byte[ms.Length];
      ms.Read(bytes, 0, bytes.Length);
      ms.Dispose();
      return bytes;
}

byte[]转bitmap:

public Bitmap ByteToBitmap(byte[] ImageByte)
{
    Bitmap bitmap = null;using (MemoryStream stream = new MemoryStream(ImageByte))        
{ bitmap = new Bitmap((Image)new Bitmap(stream)); }return bitmap; }
  • 如果只需要得到纯图像像素点位信息,则可以使用以下方式:

Bitmap转byte[]:

    /// Bitmap转byte[]
    /// 
    /// 
    private byte[] BitmapToByteArray(Bitmap bitmap)
    {
      PixelFormat pixelFormat1 = this.PixelFormat;
      System.Drawing.Imaging.PixelFormat pixelFormat2;
      if (pixelFormat1 != PixelFormat.Bgra32)
      {
        if (pixelFormat1 != PixelFormat.Bgr24)
          throw new ArgumentOutOfRangeException("PixelFormat", (object) this.PixelFormat, (string) null);
        pixelFormat2 = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
      }
      else
        pixelFormat2 = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
      System.Drawing.Imaging.PixelFormat format = pixelFormat2;
      Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
      BitmapData bitmapdata = bitmap.LockBits(rect, ImageLockMode.ReadOnly, format);
      int length = Math.Abs(bitmapdata.Stride) * bitmap.Height;
      byte[] destination = new byte[length];
      Marshal.Copy(bitmapdata.Scan0, destination, 0, length);
      bitmap.UnlockBits(bitmapdata);
      return destination;
    }

byte[]转Bitmap:

        private Bitmap ConvertFromRGBA(byte[] rgbaData, int width, int height)
        {
            var pixelFormat = PixelFormat.Format32bppRgb;
            Bitmap bitmap = new Bitmap(width, height, pixelFormat);

            BitmapData bitmapData = bitmap.LockBits(
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.WriteOnly,
                pixelFormat);

            IntPtr intPtr = bitmapData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(rgbaData, 0, intPtr, rgbaData.Length);
            bitmap.UnlockBits(bitmapData);

            return bitmap;
        }

其中注意pixelFormat两次转换必须一致。

你可能感兴趣的:(c#,java,前端,开发语言)