I am working on Windows 8 store application. I am new at it.
I am receiving an image in the form of byte array (byte []).
I have to convert this back to Image and display it in Image Control.
so far I have button and Image control on Screen. When I click button, I call following function
private async Task LoadImageAsync()
{
byte[] code = //call to third party API for byte array
System.IO.MemoryStream ms = new MemoryStream(code);
var bitmapImg = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
Windows.Storage.Streams.InMemoryRandomAccessStream imras = new Windows.Storage.Streams.InMemoryRandomAccessStream();
Windows.Storage.Streams.DataWriter write = new Windows.Storage.Streams.DataWriter(imras.GetOutputStreamAt(0));
write.WriteBytes(code);
await write.StoreAsync();
bitmapImg.SetSourceAsync(imras);
pictureBox1.Source = bitmapImg;
}
This is not working properly. any idea? When I debug, I can see the byte array in ms. but it is not getting converted to bitmapImg.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
A byte is 8 bits (binary data). A byte array is an array of bytes (tautology FTW!). You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.
In addition, you can simply convert byte array to Bitmap . var bmp = new Bitmap(new MemoryStream(imgByte)); You can also get Bitmap from file Path directly. Save this answer.
I found the following on Codeproject
public class ByteImageConverter
{
public static ImageSource ByteToImage(byte[] imageData)
{
BitmapImage biImg = new BitmapImage();
MemoryStream ms = new MemoryStream(imageData);
biImg.BeginInit();
biImg.StreamSource = ms;
biImg.EndInit();
ImageSource imgSrc = biImg as ImageSource;
return imgSrc;
}
}
This code should work for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With