przemyslaw
przemyslaw

Reputation: 21

Bitmap to byte[]

I have a problem with saving an image (or a bitmapImage or a PhotoResult) to a byte[] and then converting it back to an image.

I found a lot of posts on the internet about it but they dont work. In this code I got an Unspecifed error when I do this: SetSource ( bitmapImage.SetSource(ms);) and dont know how to do that.

I also want to make a list of Devices (each with a name, id, status and an image which I will represent as a byte[]) and save it to IsolatedStorage, and then read it and list them (with an image of course.)

Here is some code I have so far:

public void photoChooserTask_Completed(object sender, PhotoResult e)
{
    if (e.TaskResult == TaskResult.OK)
    {


        imageBytes = new byte[e.ChosenPhoto.Length];
        e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);

       BitmapImage bitmapImage = new BitmapImage();

        MemoryStream ms = new MemoryStream(imageBytes);
        try
        {
            bitmapImage.SetSource(ms);
        }
        catch (Exception ea)
        {
            //
        }
            image1.Source = bitmapImage;

    }

Upvotes: 2

Views: 500

Answers (1)

Dmitry
Dmitry

Reputation: 73

Have you tried the Microsoft.Phone.PictureDecoder class? It has a DecodeJpeg function that returns an instance of a WritableBitmap object.

Another solution is to use the WritableBitmapEx extension library that makes digital image processing much easier and has a very good performance. The function you need is called FromByteArray.

In both cases you'll have to use a WriteableBitmap, because BitmapImage is protected from modification. Since both BitmapImage and WriteableBitmap are subclasses of BitmapSource, you can easily display them in the image control.

Hope it helps!

Upvotes: 1

Related Questions