Изображение в байт [], Convert и ConvertBack - PullRequest
2 голосов
/ 21 марта 2012

У меня есть служба, которая преобразует изображения, хранящиеся на веб-сайте, в байтовый массив

                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);

Этот код возвращает байтовый массив, который я храню в базе данных (SQL Azure). В моем приложении для Windows Phone я пытаюсь преобразовать этот байтовый массив, чтобы отобразить его на своей странице.

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();
    }
}

Массив байтов хорошо воспринимается приложением, но при попытке создания SetSource выдается исключение.

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

Можете ли вы помочь мне? Thx

Ответы [ 4 ]

3 голосов
/ 21 марта 2012

Этот код работает:

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();
    }
}

Спасибо всем:)

2 голосов
/ 21 марта 2012

на эти вопросы уже ответили на stackoverflow
для изображения в байт [] попробуйте this
а для байта [] в образ попробуйте this

1 голос
/ 10 января 2013
private ImageSource GetPhoto(byte[] bytearr)
{
   if (bytearr != null)
   {
      BitmapImage image = new BitmapImage();

      InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
      ms.AsStreamForWrite().Write(bytearr, 0, bytearr.Length);
      ms.Seek(0);

      image.SetSource(ms);
      ImageSource src = image;

      return src;
   }
   else
      return null;
}
0 голосов
/ 20 марта 2017

Для моего приложения UWP я использую следующий IValueConverter для преобразования байтового массива в привязываемый объект для <Image Source={Binding} />

internal class ByteImageSourceConverter : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;
        return ByteToImage((byte[])value);
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }

    static ImageSource ByteToImage(byte[] imageBytes)
    {
        BitmapImage image = new BitmapImage();
        image.SetSource(imageBytes.ConvertToInMemoryRandomAcessStream());
        ImageSource src = image;
        return src;
    }
}

internal static InMemoryRandomAccessStream ConvertToInMemoryRandomAcessStream(this byte[] arr)
{
    var randomAccessStream = new InMemoryRandomAccessStream();
    randomAccessStream.WriteAsync(arr.AsBuffer());
    randomAccessStream.Seek(0);
    return randomAccessStream;
}

Простите за WriteAsync в синхронной функции. Для целей этого поста у меня нет времени, чтобы решить этот вопрос, но он работает следующим образом:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...