Search code examples
c#imagewindows-phone-7

Image to byte[], Convert and ConvertBack


I have a service that converts images stored on a website to byte array

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("URLTOIMAGE");
                myRequest.Method = "GET";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                Bitmap bmp = new Bitmap(myResponse.GetResponseStream());
                myResponse.Close();
                ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Bmp);

This code returns a byte array that I store in a database (SQL Azure). In my Windows Phone application, I try to convert this byte array to display it on my page.

public class BytesToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        BitmapImage empImage = new BitmapImage();
        empImage.SetSource(new MemoryStream((Byte[])value));
        return empImage;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                                System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

The byte array is well received by the application, but an exception is thrown when I try to do a SetSource.

empImage.SetSource(new MemoryStream((Byte[])value));
=> "Exception was unhandled", The request is not supported

Can you help me? Thx


Solution

  • This code works :

    public class BytesToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            MemoryStream stream = new MemoryStream((Byte[])value);
            WriteableBitmap bmp = new WriteableBitmap(173, 173);
            bmp.LoadJpeg(stream);
            return bmp;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter,
                                    System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Thank you everyone :)