C# byte[]与Bitmap互转

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

 可以看到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[]:

    /// <summary>Bitmap转byte[]</summary>
    /// <param name="bitmap"></param>
    /// <returns></returns>
    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两次转换必须一致。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值