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

}

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

回答:

嗨,这应该工作:

    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中将字节数组转换为图像 的全部内容, 来源链接: utcz.com/qa/431332.html

回到顶部