gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:37:03 24 4
gpt4 key购买 nike

我正在尝试使用本地 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com