来自url的图像到字节数组

Sha*_*500 61 c#

我有一个有图像的超链接.

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

谢谢.

Jos*_*osh 139

WebClient.DownloadData是最简单的方法.

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

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

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

  • 请注意,WebClient是一次性的,所以你应该使用`using`,如下所示:`string someUrl ="http://www.google.com/images/logos/ps_logo2.png";``using(var webClient = new WebClient()){``byte [] imageBytes = webClient.DownloadData(someUrl);``//对imageBytes``做一些事情``(对不起混乱布局.) (22认同)

Dun*_*unc 14

如果您需要异步版本:

using (var client = new HttpClient())
{
    using (var response = await client.GetAsync(url))
    {
        byte[] imageBytes =
            await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
    }
}
Run Code Online (Sandbox Code Playgroud)