惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
有赞技术团队
有赞技术团队
博客园 - 三生石上(FineUI控件)
博客园_首页
博客园 - 【当耐特】
WordPress大学
WordPress大学
月光博客
月光博客
博客园 - 叶小钗
S
SegmentFault 最新的问题
雷峰网
雷峰网
H
Help Net Security
宝玉的分享
宝玉的分享
A
About on SuperTechFans
IT之家
IT之家
J
Java Code Geeks
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 聂微东
T
The Blog of Author Tim Ferriss
B
Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog

博客园 - Zzx飘遥

发布一个注册类型库(TypeLib)的小工具 【软件发布】发布一个查单词的小工具 COM 入门(4) COM 入门(3) COM 入门(2) COM 入门(1) C#内嵌汇编代码的讨论 仿Win7显示桌面的工具 Deep Zoom Composer初探 ASP.NET VirtualPathProvider (下) Silverlight3离线运行 [译]理解Windows消息循环 VC++中启用XP主题外观 C#4.0初探:dynamic 关键字 - Zzx飘遥 - 博客园 四个字节整型转换为IP格式 - Zzx飘遥 - 博客园 拯救开启桌面效果后白屏的openSUSE 遭遇SqlDataReader锁定表 软件更新:网页设计师必备 之 网站截图工具 (附源码) C#4.0初探: Optional and named parameters
WPF BitmapImage与byte[]的转换
Zzx飘遥 · 2009-06-25 · via 博客园 - Zzx飘遥

有时要实现BitmapImage与byte[]相互转换,这里实现两个静态方法,直接调用即可。

byte[]转换为BitmapImage:

public static BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
{
    BitmapImage bmp
= null; try
    {
        bmp
= new BitmapImage();
        bmp.BeginInit();
        bmp.StreamSource
= new MemoryStream(byteArray);
        bmp.EndInit();
    }
    
catch
    {
        bmp
= null;
    }
return bmp;
}

BitmapImage转换为byte[]:

public static byte[] BitmapImageToByteArray(BitmapImage bmp)
{
    
byte[] byteArray = null; try
    {
        Stream sMarket
= bmp.StreamSource; if (sMarket != null && sMarket.Length > 0)
        {
            
//很重要,因为Position经常位于Stream的末尾,导致下面读取到的长度为0。
            sMarket.Position = 0; using (BinaryReader br = new BinaryReader(sMarket))
            {
                byteArray
= br.ReadBytes((int)sMarket.Length);
            }
        }
    }
    
catch
    {
        
//other exception handling
    } return byteArray;
}