将字节数组转换为

将字节数组转换为

本文介绍了将字节数组转换为 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 中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:42