从字节数组创建BitmapImage [英] Creating BitmapImage from array of bytes

查看:101
本文介绍了从字节数组创建BitmapImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我需要一个函数将存储在字节数组中的图像数据转换为可以使用某些WPF控件显示的格式。字节数组包含存储在硬盘上的图像数据,因此还有标题数据。我已经有了System.Drawing.Image的代码,它工作正常,我试着写一个WPF模拟它。



目前,我有这个:

Hello everybody,

I needed a function to convert image data stored in byte array to a format, that can be displayed using some WPF controls. The byte array contains image data as is stored on harddisk, so there're also the header data. I've already had the code for System.Drawing.Image, which worked fine and I tried to write a WPF analogue to it.

Currently, I have this:

public static BitmapImage ToBitmapImage(this byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {

                BitmapImage img = new BitmapImage();
                img.CacheOption = BitmapCacheOption.OnLoad;
                img.BeginInit();
                img.StreamSource = ms;
                img.EndInit();

                if (img.CanFreeze)
                {
                    img.Freeze();
                }


                return img;
            }
        }







BitmapImage bd = myimage.ToBitmapImage();
imgCtrl.Source = bd;//imgCtrl is WPF's Image control





问题是,图像不显示。我尝试了不同的CacheOptions,但它没有帮助。也许这只是一些小事,但我不知道那是什么。提前谢谢:)。



解决方案

在我的情况下,只需要稍微调整一下代码工作。 CacheOption应该在BeginInit()之后设置,而不是在调用它之前。



The problem is,that the image is not displayed. I've tried different CacheOptions, but it didn't help. Maybe it's just some little thing, but I've no idea what is that. Thank you in advance :).

Solution
In my case, only a little tweak was needed and the code worked. CacheOption should be set after BeginInit(), not before calling it.

public static BitmapImage ToBitmapImage(this byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {

                BitmapImage img = new BitmapImage();
                img.BeginInit();
                img.CacheOption = BitmapCacheOption.OnLoad;//CacheOption must be set after BeginInit()
                img.StreamSource = ms;
                img.EndInit();

                if (img.CanFreeze)
                {
                    img.Freeze();
                }


                return img;
            }
        }

推荐答案

我使用了一些不同的方法。首先将位图保存到内存流中,然后转换为图像。



查看如何从Office文档中提取图像 [ ^ ]
I've used a bit different approach. First saving the bitmap into the memory stream and then converting to image.

Have a look at the last code block in How To Extract Images From An Office Document[^]


这篇关于从字节数组创建BitmapImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆