C#: Convert all images in a folder from PNG to JPG

How to convert all images in a folder from PNG to JPG.

This method is written in C#. Input a folder path. The code will then find all files with .png file extensions in that folder, and save them again as .jpg files. Original files will not be deleted.

The Image.Save method allows for a wide range of image formats including bmp, tiff and gif. You can edit the code below for your own file formats.

C# method to convert images to JPG

        /// <summary>
        /// Converts all images in a folder to JPG
        /// </summary>
        /// <param name="folder">String representing folder location</param>
        public void ToJPG(string folder)
        {

            foreach (string file in System.IO.Directory.GetFiles(folder))
            {
                string extension = System.IO.Path.GetExtension(file);
                if (extension == ".png")
                {
                    string name = System.IO.Path.GetFileNameWithoutExtension(file);
                    string path = System.IO.Path.GetDirectoryName(file);
                    Image png = Image.FromFile(file);
                    png.Save(path + @"/" + name + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    png.Dispose();
                }
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.