C# Bitmap与byte[]相互转换

Bitmap转换为byte[]

private byte[] BitmapToBytes(Bitmap bitmap)
        {
            // 1.先将BitMap转成内存流
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);
            // 2.再将内存流转成byte[]并返回
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            ms.Dispose();
            return bytes;
        }

byte[]转换为Bitmap

private System.Drawing.Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new System.Drawing.Bitmap((System.Drawing.Image)new System.Drawing.Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

在查阅如何转换的时候被坑了,下面是错误的byte[]转换为Bitmap

private System.Drawing.Bitmap ByteToBitmap(byte[] bytes)
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
     System.Drawing.Bitmap bitmap =     (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms);
     ms.close();
     return bitmap;
 }

使用此代码转换时无法Save图像

转载自C# Bitmap 与 Bytes数组,Bitmap与Image 控件的转换_楚楚3107的博客-CSDN博客_bitmap byte数组icon-default.png?t=M3C8https://blog.csdn.net/chulijun3107/article/details/115177992

 

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值