Hi,@mc. Welcome Microsoft Q&A. Here are some solutions that may work for you in WPF.
You could load the byte array into a MemoryStream
and then create a BitmapImage
from that MemoryStream
. This approach should work with various common image formats.
Load the byte array into a MemoryStream
.
public BitmapImage ToImage(byte[] array)
{
using (var ms = new System.IO.MemoryStream(array))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
return image;
}
}
From the Remarks section in BitmapImage.StreamSource:
Set the CacheOption property to BitmapCacheOption.OnLoad if you wish to close the stream after the BitmapImage is created.
Besides that, you can also use built-in type conversion to convert from type byte[] to type ImageSource (or the derived BitmapSource):
var bitmap = (BitmapSource)new ImageSourceConverter().ConvertFrom(array);
Method that uses the ImageConverter object in .Net Framework to convert a byte array, presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be used as an Image object.
/// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
Or you can refer to the solution here to see if it is helpful to you.
If you still have questions, please feel free to let me know.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.