Find file extension from System.Drawing.Image object


You may have worked with System.Drawing.Image object to edit or save images. This C# sample code shows how to find the image extension from the System.Drawing.Image object so that you can save it with correct file extension.

The below C# code sample shows how to identify the file format and extension from the System.Drawing.Image object and save to a folder with correct extension.


System.Drawing.Image image = DownloadImageFromUrl(txtUrl.Text.Trim());

string fileName = Guid.NewGuid().ToString();

if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
{
fileName = fileName + ".jpg";
}
else if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
{
fileName = fileName + ".gif";
}
else if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
{
fileName = fileName + ".png";
}
else if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
{
fileName = fileName + ".bmp";
}
// handle other image formats as well....


The above C# code snippet uses a method to get the Image object. The code for this method can be found in another C# sample here DownloadImageFromUrl(url).

You can easily convert this C# code sample to VB.NET using our C# to VB.NET code converter.


Related Articles

Download images from a URL using C#

Many times you may wanted to share an image from an external website, but found it hard to download it first to your local computer and then upload to your blog or website? This C# code sample shows how to programmatically download an image from a website and save to your website on your web server.

More articles: Image Editing

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: