.NET: Convert Image Formats Programmatically

Tuesday, July 07, 2009

Using the .NET framework, you can easily convert images from one format to another with just a few lines of code. The System.Drawing namespace has the functions which help you to load and then save the image in the desired format. The formats supported by the ImageFormat class are: Bmp, Emf, Exif, Gif, Guid, Icon, Jpeg, MemoryBmp, Png, Tiff, Wmf. You can convert an image to any of these formats.

Here is a simple console application which reads all files in a given directory and converts them into .jpg images. It includes the System.IO namespace to read the files in the directory and the System.Drawing class for image functions. You would need to add a reference to System.Drawing class in the Console application. Also, make sure you only have images in the directory or specify a check in the code to read only image files.

// C#
using System.IO;
using System.Drawing;

static class Module1
    public static void Main()
        DirectoryInfo dir = new DirectoryInfo("C:\\something");
        foreach (FileInfo img in dir.GetFiles) {
            Image _image = Image.FromFile("C:\\something\\" + img.Name);
            _image.Save(img.Name, Imaging.ImageFormat.Jpeg);
Imports System.IO
Imports System.Drawing

Module Module1

Sub Main()
Dim dir As New DirectoryInfo("C:\something")

For Each img As FileInfo In dir.GetFiles
Dim _image As Image = Image.FromFile("C:\something\" & img.Name)
_image.Save(img.Name, Imaging.ImageFormat.Jpeg)
End Sub

End Module

The output files would be written into your 'bin' directory if you execute this code from Visual Studio. If you need to change the output path, you can do so by adding a Path to the Save method.


Post a Comment