如何使用 httpwebrequest 将图像从网站拉到本地文件 [英] How to use httpwebrequest to pull image from website to local file

查看:18
本文介绍了如何使用 httpwebrequest 将图像从网站拉到本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用本地 c# 应用程序将一些图像从网站上提取到本地计算机上的文件中.我正在使用下面列出的代码.我已经尝试了 ASCII 编码和 UTF8 编码,但最终文件不正确.有没有人看到我做错了什么?当我将地址放入浏览器时,该 url 处于活动状态且正确无误,并且可以很好地显示图像.

I'm trying to use a local c# app to pull some images off a website to files on my local machine. I'm using the code listed below. I've tried both ASCII encoding and UTF8 encoding but the final file is not an correct. Does anyone see what I'm doing wrong? The url is active and correct and show the image just fine when I put the address in my browser.

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

推荐答案

nice image :D

nice image :D

尝试使用以下代码:

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

you needed to use a BinaryReader, 'cause an image file is binary data and thus not encoded in UTF or ASCII

使用'化

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

这篇关于如何使用 httpwebrequest 将图像从网站拉到本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆