转换的字节数组图像WPF [英] Convert byte array to image in wpf

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

问题描述

我用

private BitmapImage byteArrayToImage(byte[] byteArrayIn)
{
    try
    {               
        MemoryStream stream = new MemoryStream();
        stream.Write(byteArrayIn, 0, byteArrayIn.Length);
        stream.Position = 0;
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        BitmapImage returnImage = new BitmapImage();
        returnImage.BeginInit();
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        ms.Seek(0, SeekOrigin.Begin);
        returnImage.StreamSource = ms;
        returnImage.EndInit();

        return returnImage;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return null;
}

这方法我的应用程序的字节数组转换为图像。但将参数无效异常..为什么它正在发生..?是否有任何其他方法??

This method in my application to convert byte array to an image. But it throws "Parameter is not valid" exception.. why it is happening..? Is there any alternative method.??

推荐答案

你好,这应该是工作:

    private static BitmapImage LoadImage(byte[] imageData)
    {
        if (imageData == null || imageData.Length == 0) return null;
        var image = new BitmapImage();
        using (var mem = new MemoryStream(imageData))
        {
            mem.Position = 0;
            image.BeginInit();
            image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = null;
            image.StreamSource = mem;
            image.EndInit();
        }
        image.Freeze();
        return image;
    }

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

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