C#中Byte[]数组、BitmapImage、BitmapSource互转
原文: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(); }
3、BitmapImage和byte[]相互转换
// BitmapImage --> byte[] public static byte[] BitmapImageToByteArray(BitmapImage bmp) { byte[] bytearray = null; try { Stream smarket = bmp.StreamSource; ; if (smarket != null && smarket.Length > 0) { //设置当前位置 smarket.Position = 0; using (BinaryReader br = new BinaryReader(smarket)) { bytearray = br.ReadBytes((int)smarket.Length); } } } catch (Exception ex) { Console.WriteLine(ex); } return bytearray; }
编程是个人爱好
分类:
WPF / XAML
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
2021-11-18 【C# IO 操作】C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
2021-11-18 【C# IO 操作】使用StringWriter和StringReader的好处