Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert byte array to ImageSource for Windows 8.0 store application

Tags:

windows

c#-4.0

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.

like image 999
Developer Avatar asked Feb 27 '14 10:02

Developer


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do I convert an image to a Bytearray?

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.

What does byte array store?

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.

How do I convert a bitmap to a byte?

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.


1 Answers

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.

like image 144
Tomtom Avatar answered Sep 28 '22 09:09

Tomtom