【发布时间】:2022-02-27 14:47:32
【问题描述】:
我有一个带有图像的超链接。
我需要从该超链接读取/加载图像并将其分配给 C# 中的字节数组 (byte[])。
谢谢。
【问题讨论】:
标签: c#
我有一个带有图像的超链接。
我需要从该超链接读取/加载图像并将其分配给 C# 中的字节数组 (byte[])。
谢谢。
【问题讨论】:
标签: c#
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`} 相关的东西(对不起,布局混乱。)
如果您需要异步版本:
using (var client = new HttpClient())
{
using (var response = await client.GetAsync(url))
{
byte[] imageBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
}
【讨论】:
.NET 4.5 引入了 WebClient.DownloadDataTaskAsync() 用于异步使用。
例子:
using ( WebClient client = new WebClient() )
{
byte[] bytes = await client.DownloadDataTaskAsync( "https://someimage.jpg" );
}
【讨论】:
试试下面的方法:
public byte[] UdfGetByteFromImageURL(String StrImageUrl)
{
using (var webClient = new WebClient())
{
byte[] imageBytes = webClient.DownloadData(StrImageUrl);
return imageBytes;
}
}
【讨论】: