【问题标题】:Image to byte array from a url从 url 到字节数组的图像
【发布时间】:2022-02-27 14:47:32
【问题描述】:

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

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

谢谢。

【问题讨论】:

    标签: c#


    【解决方案1】:

    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);
    }
    

    【讨论】:

    • 谢谢,我越来越近了,没有得到图像字节,如果你举一些简单的例子会很有帮助。
    • 那你得到了什么?您可能需要一个名为 Fiddler 的工具,它会向您显示可能帮助您解决问题的请求和响应。它真的没有比 WebClient.DownloadData 更简单的了。
    • 谢谢,但我得到“远程服务器返回错误:(404)未找到。”
    • 然后查看 Fiddler,看看您是否能发现在浏览器中执行此操作与通过代码执行此操作之间的区别。 404 通常表示您的 URL 错误。
    • 请注意,WebClient 是一次性的,所以您应该使用using,如下所示:string someUrl = "http://www.google.com/images/logos/ps_logo2.png"; using (var webClient = new WebClient()) { ` byte[] imageBytes = webClient.DownloadData(someUrl);` ` // 做与 imageBytes`} 相关的东西(对不起,布局混乱。)
    【解决方案2】:

    如果您需要异步版本:

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

    【讨论】:

      【解决方案3】:

      .NET 4.5 引入了 WebClient.DownloadDataTaskAsync() 用于异步使用。

      例子:

      using ( WebClient client = new WebClient() )
      {
        byte[] bytes = await client.DownloadDataTaskAsync( "https://someimage.jpg" );
      }
      
      

      【讨论】:

        【解决方案4】:

        试试下面的方法:

        public byte[] UdfGetByteFromImageURL(String StrImageUrl)
        {
            using (var webClient = new WebClient()) 
            { 
                    byte[] imageBytes = webClient.DownloadData(StrImageUrl);
                return imageBytes;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-25
          • 2012-07-28
          • 1970-01-01
          • 1970-01-01
          • 2012-05-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多