首页 新闻 会员 周边

WPF byte[] 转 BitmapImage 问题。

0
[待解决问题]


方法1:
 public static BitmapImage GetImage(byte[] buffer)
        {
            if (buffer == null || buffer.Length <= 0)
                return null;

            BitmapImage bitmap = null;
            try
            {
                bitmap = new BitmapImage();
                bitmap.DecodePixelHeight = 200; // 确定解码高度,宽度不同时设置
                bitmap.BeginInit();

                bitmap.CacheOption = BitmapCacheOption.OnLoad;

                using (Stream ms = new MemoryStream(buffer))
                {
                    bitmap.StreamSource = ms;
                    bitmap.EndInit();
                    bitmap.Freeze();

                    ms.Dispose();
                }
            }
            catch (Exception ex)
            {
                LogManager.Log.WriteLog(LogFile.Error, string.Format("{0}", ex));
                bitmap = null;
            }

            return bitmap;
        }

方法2:
 public static BitmapImage GetImage(byte[] buffer)
        {
            if (buffer == null || buffer.Length <= 0)
                return null;

            BitmapImage bitmap = new BitmapImage();
            bitmap.DecodePixelHeight = 200; // 确定解码高度,宽度不同时设置
            bitmap.BeginInit();

            bitmap.CacheOption = BitmapCacheOption.OnLoad;

            using (Stream ms = new MemoryStream(buffer))
            {
                 bitmap.StreamSource = ms;
                 bitmap.EndInit();
                 bitmap.Freeze();

                 ms.Dispose();
            }
            return bitmap;
        }

方法1、方法2 都一样,只是在方法1中多了一个try{} catch(){} 。但在使用过程中,调用方法2的时候,图片byte[] 转换成 BitmapImage 的时候,就会出错:
Exception object: 00000000031b78b8
Exception type:   System.IO.IOException
Message:          无法从流中读取。

而同样的图片,在调用方法1 的时候,就不会有问题,求教有什么不同?

☆☋的主页 ☆☋ | 菜鸟二级 | 园豆:202
提问于:2017-06-30 14:34
< >
分享
所有回答(1)
0

你看看方法1是不是返回null,你方法1已经把异常埋了

MrNice | 园豆:3450 (老鸟四级) | 2017-06-30 14:52

嗯,是的,谢谢

支持(0) 反对(0) ☆☋ | 园豆:202 (菜鸟二级) | 2017-06-30 18:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册