gpt4 book ai didi

c# - 将 byte[] 转换为图像 Windows Phone

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:38 24 4
gpt4 key购买 nike

当我想从字节数组“创建”图像到 image.Source (XAML) 时,我遇到了一个小问题...首先我从 web 保存字节数组

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

有人知道怎么解决吗?先谢谢了

最佳答案

如果您的 byte[] 图像 是 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;
}

关于c# - 将 byte[] 转换为图像 Windows Phone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26483249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com