WebP image with C# ImageFormat class

前端 未结 2 2020
后悔当初
后悔当初 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!

    0 讨论(0)
  • 2021-01-24 01:00

    The base class libraries won't help you to deal with WebP images. However, if you only want to save the received file to the disk, you don't have to even know that you are dealing with a WebP images. You can simply treat the received data as a binary blob and dump it to a file, for example using Stream.CopyTo and a FileStream.

    The Content-Type HTTP header will give you the mime type of the file you're downloading, and the Content-Disposition header can provide you with a filename and extension (though you might have to do some parsing). You can access those using HttpWebResponse.ContentType and HttpWebResponse.Headers["Content-Disposition"].

    0 讨论(0)
提交回复
热议问题