• 欢迎光临~

C#中Byte[]数组、BitmapImage、BitmapSource互转

开发技术 开发技术 2022-11-18 次浏览

原文:https://blog.csdn.net/dap769815768/article/details/127105330?spm=1001.2014.3001.5502

1.byte数组转BitmapImage

常用的Byte数组转图像的方法如下:

        public BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
        {
            using (Stream stream = new MemoryStream(byteArray))
            {
                BitmapImage image = new BitmapImage();
                stream.Position = 0;
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = stream;
                image.EndInit();
                image.Freeze();
                return image;
            }
        }

这个方法只能够转本身带有图像格式信息byte数组,不然就会报错,比如用如下数组进行转图操作:

image.Source = ByteArrayToBitmapImage(new byte[500*500]);

报错信息如下:

COMException: 无法找不到组件。 (异常来自 HRESULT:0x88982F50)

2.图片转byte数组。

方法较多,思路就是把图像读入到stream里面,将stream转换成Byte数组。

比如如下一种方式:

FileStream fs = new FileStream("test.jpg", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imgBytes = br.ReadBytes((int)fs.Length);

或者:

        public byte[] ImageToByteArray(Bitmap image)
        {
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }

 

程序员灯塔
转载请注明原文链接:C#中Byte[]数组、BitmapImage、BitmapSource互转
喜欢 (0)
违法和不良信息举报电话:022-22558618 举报邮箱:dljd@tidljd.com