我有一个带有图像的超链接。
我需要从该超链接读取/加载图像,并将其分配给byte[]C#中的字节数组()。
谢谢。
Answers:
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);
}
using这样:string someUrl = "http://www.google.com/images/logos/ps_logo2.png"; using (var webClient = new WebClient()) { `byte [] imageBytes = webClient.DownloadData(someUrl);`//使用imageBytes做一些事情 }(对不起,布局混乱。)
.NET 4.5引入了WebClient.DownloadDataTaskAsync()用于异步使用。
例:
using ( WebClient client = new WebClient() )
{
byte[] bytes = await client.DownloadDataTaskAsync( "https://someimage.jpg" );
}