图片从网址到字节数组


71

我有一个带有图像的超链接。

我需要从该超链接读取/加载图像,并将其分配给byte[]C#中的字节数组()。

谢谢。

Answers:


154

WebClient.DownloadData是最简单的方法。

var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");

第三方编辑:请注意,WebClient是一次性的,因此您应该使用using

string someUrl = "http://www.google.com/images/logos/ps_logo2.png"; 
using (var webClient = new WebClient()) { 
    byte[] imageBytes = webClient.DownloadData(someUrl);
}

谢谢,越来越近了,没有得到图像字节,如果您举一些简单的例子,将会对您有很大帮助。
Sharpeye500

那你得到什么?您可能想要使用一个名为Fiddler的工具,该工具将向您显示可以帮助您解决问题的请求和响应。它确实比WebClient.DownloadData更简单。
乔什(Josh)

谢谢,但是我得到“远程服务器返回错误:(404)找不到。”
Sharpeye500

然后检查Fiddler,看看您是否可以发现在浏览器中进行操作与通过代码进行操作之间的区别。404通常表示您输入了错误的URL。
乔什

22
请注意,WebClient是一次性的,因此您应该using这样:string someUrl = "http://www.google.com/images/logos/ps_logo2.png"; using (var webClient = new WebClient()) { `byte [] imageBytes = webClient.DownloadData(someUrl);`//使用imageBytes做一些事情 }(对不起,布局混乱。)
Bondt


0

如果需要异步版本:

using (var client = new HttpClient())
{
    using (var response = await client.GetAsync(url))
    {
        byte[] imageBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
     }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.