从图像转换到byte[]数组的几种方法

本文介绍三种将图片转换为字节数组的方法,并对比它们的性能特点。第一种方法通过锁定位图获取像素数据,性能最高;第二种方法使用ImageConverter,数组内容较少且未知;第三种方法通过内存流保存图片为特定格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 性能最高,其数组和像素一一对应
public static void test1(Image img)
        {
            Bitmap bmp 
= new Bitmap(img);
            BitmapData bitmapData 
= bmp.LockBits(new Rectangle(new Point(00), img.Size), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            
byte[] BGRValues = new byte[bitmapData.Stride * bitmapData.Height];

            IntPtr Ptr 
= bitmapData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(Ptr, BGRValues, 
0, BGRValues.Length);

            bmp.UnlockBits(bitmapData);
        }

// 性能较低,数组内容较少,内容未知
        public static void test2(Image img)
        {
            System.Drawing.ImageConverter ic 
= new System.Drawing.ImageConverter();
            
byte[] btImage1 = new byte[0];
            btImage1 
= (byte[])ic.ConvertTo(img, btImage1.GetType());
        }

// 性能较低,数组内容为图片格式内容,格式未知
        public static void test3(Image img)
        {
            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            img.Save(ms,ImageFormat.Bmp);
            
byte[] byteImage = new Byte[0];
            byteImage 
= ms.ToArray();
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值