我正在从URL获取图像:
BitmapImage image = new BitmapImage(new Uri(article.ImageURL));
NLBI.Thumbnail.Source = image;
这工作完美,现在我需要将其放入流中,以使其成为字节数组。我正在这样做:
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
并且NullReference代码失败,如何解决?
最佳答案
您会收到NullReference
异常,因为使用该图像时仍未加载该图像。您可以等待ImageOpened
事件,然后使用它:
var image = new BitmapImage(new Uri(article.ImageURL));
image.ImageOpened += (s, e) =>
{
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
};
NLBI.Thumbnail.Source = image;
另一个选择是使用WebClient直接获取图像文件的流:
WebClient client = new WebClient();
client.OpenReadCompleted += (s, e) =>
{
byte[] imageBytes = new byte[e.Result.Length];
e.Result.Read(imageBytes, 0, imageBytes.Length);
// Now you can use the returned stream to set the image source too
var image = new BitmapImage();
image.SetSource(e.Result);
NLBI.Thumbnail.Source = image;
};
client.OpenReadAsync(new Uri(article.ImageURL));
关于c# - 图片从URL到流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17876015/