DEV Community

Zaw
Zaw

Posted on • Updated on

Converting PNG to JPG image files in C#

If you are a programmer and you have hundreds of PNG files occupying your storage disk, you can save some space by converting PNG to JPG files, provided that you're not concerned about reducing some non-visible quality.

Here are the steps you can code that program in C#.

In bash/console terminal,

mkdir png2jpg
cd png2jpg
dotnet new console
dotnet add package System.Drawing.Common
code .

Add new using statements in Program.cs,

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

Add the following code in main program.

            var folder = @"/Users/PNGs/";
            int count = 0;

            foreach (string file in Directory.GetFiles(folder))
            {
                string ext = Path.GetExtension(file).ToLower();
                if (ext == ".png")
                {
                    Console.WriteLine(file);
                    string name = Path.GetFileNameWithoutExtension(file);
                    string path = Path.GetDirectoryName(file);

                    Image png = Image.FromFile(file);

                    png.Save(path + @"/" + name + ".jpg", ImageFormat.Jpeg);
                    png.Dispose();

                    count++;
                    File.Delete(file);

                }
            }

            Console.WriteLine("{0} file(s) converted.", count);
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();

What this code does is it will get the path to the PNG directory. It will check the files one by one whether it has a PNG extension. When the PNG file is found, it will split the name and the path of that file. And save the file with the extension, JPG and its format. Then it will finalize the image and delete the PNG accordingly.

If you are using macOS, you may need to install mono-libgdiplus. If I've missed some Exception Handling, please let me know. Thanks for reading.

Top comments (1)

Collapse
 
glihm profile image
glihm

Short and efficient. :)

Little suggestion, Path.Combine might be cleaner than string concatenation when you save the png. :)