开发者

How to get file extension from Save file dialog?

开发者 https://www.devze.com 2023-02-10 03:25 出处:网络
I wo开发者_JAVA技巧uld like to be able to save image according to extension that is entered in the save file dialog. I have found out that simply entering e.g. \"JPG\" does not cause the Save method t

I wo开发者_JAVA技巧uld like to be able to save image according to extension that is entered in the save file dialog. I have found out that simply entering e.g. "JPG" does not cause the Save method to use this format of course. Parsing the extension and then using e.g. switch and setting correct format sounds a bit ackward to me. Or there is no better way?


you can get the file name specified in the SaveDialog.FileName then with Path.GetExtension() or similar you can get the string which will be used as extension.

What you will do after depends on your specific application design, if you are saving a text file you can also call it image1.png, but it will still be a text file.

if you have an image object in memory and want to save in the proper format depending on the selected extension, I would use a switch/case and use the proper overload or parameter values of the Image.Save to handle the different image formats.

Example

if(DialogResult.OK == saveDialog.ShowDialog())
{
    var extension = Path.GetExtension(saveDialog.FileName);

    switch(extension.ToLower())
    {
        case ".jpg":
            // ToDo: Save as JPEG
            break;
        case ".png":
            // ToDo: Save as PNG
            break;
        default:
            throw new ArgumentOutOfRangeException(extension);
    }
}


After getting the extension, as @David suggested, you should then map it to the MIME type, see http://kseesharp.blogspot.com/2008/04/c-get-mimetype-from-file-name.html. This allows you to cope with multiple extensions, such as ".jpg" and ".jpeg".

You will then have to save the image with the correct encoder, see http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing

It is late in NZ and I can't be stuffed with writing an example. But, if you really need an example tell me and I will provide one tomorrow.

0

精彩评论

暂无评论...
验证码 换一张
取 消