从URL到流的图像
我从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
exception,因为在使用它时图像仍未加载。 您可以等待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));
var webClient = new WebClient(); byte[] imageBytes = webClient.DownloadData(article.ImageURL);
你可以用这个:
private async Task GetImageAsByteArray(string urlImage, string urlBase) { var client = new HttpClient(); client.BaseAddress = new Uri(urlBase); var response = await client.GetAsync(urlImage); return await response.Content.ReadAsByteArrayAsync(); }
- 将xelement加载到数据表中
- 将字符串转换为小数分隔符的最佳方法“。”和“,”不敏感的方式?
- 添加自定义请求标头适用于IIS 7.0但不适用于Asp.net开发服务器
- 如何在C#中将子表单的子数据传递给父表单?
- 在.net打印预览对话框中禁用“打印”按钮
- ASP.NET MVC 2 – 使用UpdateModel和LINQ to Entities(.NET 3.5)时,“无法更新类型’XYZ’的模型”
- Application.Restart()是否为应用程序创建新进程或没有?
- 如何从Visual Studio 2012项目降级到Visual Studio 2008
- 在C#中,OptionalField已经过时了?