DEV Community

Zaw
Zaw

Posted on • Edited on

10 1

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 .
Enter fullscreen mode Exit fullscreen mode

Add new using statements in Program.cs,

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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. :)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay