WebP image with C# ImageFormat class

前端 未结 2 2022
后悔当初
后悔当初 2021-01-24 00:27

I\'m downloading in image from web to save it locally. It works great with any other image formats but it this method below fails with an argument exception when I try to read a

2条回答
  •  离开以前
    2021-01-24 00:46

    @Trillian nailed it. Here is a code snippet for what I did based on his suggestion. Wanted to add code so not posting this as a comment.

    To get just the image file extension, you can do this

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();    
    string fileExt = response.ContentType.Replace("image/", string.Empty);            
    

    To get the file name with extension, you can do the following and the do parsing like I did above. It just has some more data in it.

    response.Headers["Content-Disposition"];
    

    Once you have you file name you want to save as, create a file stream and copy the response stream into it.

    FileStream fs = new FileStream(targetPath + fileName, FileMode.Create);
    response.GetResponseStream().CopyTo(fs);
    

    Assuming you app has access to the destination, image should get saved. Make sure to add try catch and handle exceptions properly. Also note that FileMode.Create will overwrite if the file already exists!

提交回复
热议问题