将字节数组转换为图像

将字节数组转换为图像

我用了

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;
}

在我的应用程序中,此方法将字节数组转换为图像。但是它抛出“参数无效”异常。为什么会发生..?有其他替代方法吗??

最佳答案

嗨,这应该工作:

    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;
    }

关于c# - 在wpf中将字节数组转换为图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9564174/

10-08 20:48