c# - 如何使用httpwebrequest从网站拉取图片到本地文件

标签 c# image file httpwebrequest

我正在尝试使用本地 C# 应用程序将网站上的一些图像提取到本地计算机上的文件中。我正在使用下面列出的代码。我试过 ASCII 编码和 UTF8 编码,但最终文件不正确。有没有人看到我做错了什么?当我将地址放入浏览器时,该 url 是有效且正确的并且可以正常显示图像。

    private void button1_Click(object sender, EventArgs e)
    {
        HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create("http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg");

        // returned values are returned as a stream, then read into a string
        String lsResponse = string.Empty;
        HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse();
        using (StreamReader lxResponseStream = new StreamReader(lxResponse.GetResponseStream()))
        {
            lsResponse = lxResponseStream.ReadToEnd();
            lxResponseStream.Close();
        }

        byte[] lnByte = System.Text.UTF8Encoding.UTF8.GetBytes(lsResponse);

        System.IO.FileStream lxFS = new FileStream("34891.jpg", FileMode.Create);
        lxFS.Write(lnByte, 0, lnByte.Length);
        lxFS.Close();

        MessageBox.Show("done");
    }

最佳答案

漂亮的图片:D

尝试使用以下代码:

您需要使用 BinaryReader,因为图像文件是二进制数据,因此没有以 UTF 或 ASCII 编码

编辑:使用'ified

HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(
"http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg");

// returned values are returned as a stream, then read into a string
String lsResponse = string.Empty;
using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse()){
   using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream())) {
      Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
      using (FileStream lxFS = new FileStream("34891.jpg", FileMode.Create)) {
          lxFS.Write(lnByte, 0, lnByte.Length);
      }
   }
}
MessageBox.Show("done");

关于c# - 如何使用httpwebrequest从网站拉取图片到本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2368115/

相关文章:

c# - 我可以只对整个项目使用通用存储库和通用服务类吗?

c# - 是否有任何简单的方法可以从内部将值分配给模型列表?

c# - 将 Javascript JSON 转换为 .NET 整数数组

javascript - 从 url 获取图像并使用 javascript 转换为 blob

java - 在 Java 中快速加载部分大图像

java - 追加到文件并从文件读取,但没有任何反应

c# - 在不使用静态类的情况下调用类的扩展方法,而是使用反射使用类 iteslf

Android,mdpi密度但屏幕不同

python - 我可以在 python 中为 tempfile.NamedTemporaryFile 设置 umask 吗?

javascript - 如何通过将 AJAX 中的 <input type ="file"> 数据放入对象中来发送它?