无法使用位图下载图像

时间:2019-06-03 11:24:01

标签: c# bitmap

我的代码:

var imagePath = Path.Combine(Config.FtpFolder, filePath);
WebClient wc = new WebClient();
wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)");
wc.Headers.Add("Accept", "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
Stream s = new MemoryStream(wc.DownloadData(url));
Bitmap bmp = new Bitmap(s);
bmp.Save(imagePath);
bmp.Dispose();
wc.Dispose();

数据:

url = "https://vnn-imgs-a1.vgcloud.vn/photo-2-baomoi.zadn.vn/w700_r1/2019_06_01_287_30932992/eb8b020b0f4be615bf5a.jpg"
imagepath = C:\image1\2019/06/03\anhdaidien-5(2).jpg

跑步时出现错误

  

ERR参数无效。在System.Drawing.Bitmap..ctor(流流)处

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

文档(https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.-ctor?view=netframework-4.8#System_Drawing_Bitmap__ctor_System_IO_Stream_)建议您可以执行自己的操作,因此您尝试下载的图像可能有问题,或者流中包含HTTP标头?

这是文档中的代码,与您的代码略有不同,但是应该可以:

try
{
    System.Net.WebRequest request = 
        System.Net.WebRequest.Create(
        "http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif");
    System.Net.WebResponse response = request.GetResponse();
    System.IO.Stream responseStream = 
        response.GetResponseStream();
    Bitmap bitmap2 = new Bitmap(responseStream);
    PictureBox1.Image = bitmap2;

}
catch(System.Net.WebException)
{
    MessageBox.Show("There was an error opening the image file."
       + "Check the URL");
}