将byte []转换为图像Windows Phone

时间:2014-10-21 09:26:08

标签: c# windows-phone-8

当我想要创造"我有一点问题。从字节数组到image.Source(XAML)的图像...... 我从网上保存字节数组

string pomocna = responseS.GetValue("slika").ToString();
            byte[] pomocnoPolje = new byte[pomocna.Length];
            int brojac = 0;
            foreach (char a in pomocna)
            {
                pomocnoPolje[brojac] = byte.Parse(a.ToString());
                brojac++;
            }
            nova.slika = pomocnoPolje;

然后我设置了图像源

stranica.slika.Source = ConvertToBitmapImage(nova.slika)

我的ConvertToBitmapImage方法出现问题

public static BitmapImage ConvertToBitmapImage(byte[] image)
    {
        var bitmapImage = new BitmapImage();
        var memoryStream = new MemoryStream(image);
        bitmapImage.SetSource(memoryStream);
        return bitmapImage;
    }

就行了

bitmapImage.SetSource(memoryStream);

有谁知道如何修复它? 提前谢谢

1 个答案:

答案 0 :(得分:0)

如果您的byte[] image是JPEG,并且您希望保留内存流,请执行以下操作:

public static BitmapImage ConvertToBitmapImage(byte[] image)
{
    WriteableBitmap wb = null;

    using (MemoryStream ms = new MemoryStream(image))
    {
        try
        {
            wb = Microsoft.Phone.PictureDecoder.DecodeJpeg(ms);
        }
        catch (Exception ex)
        {
            string error_message = ex.Message;
        }
    }

    return ConvertWBtoBI(wb);
}

// converts a WriteableBitmap to a BitmapImage
private BitmapImage ConvertWBtoBI(WriteableBitmap wb)
{
    if(wb == null)
       return null;

    BitmapImage bi;

    using (MemoryStream ms = new MemoryStream())
    {
        wb.SaveJpeg(ms, wb.PixelWidth, wb.PixelHeight, 0, 100);
        bi = new BitmapImage();
        bi.SetSource(ms);
    }

    return bi;
}