06 January, 2023

Improve Image Quality with C#

How to increase the resolution of an image in C#?

 Improving the resolution of an image, also known as upscaling or resampling, can be challenging as it involves adding new pixels to the image, which can lead to a loss of quality if not done carefully. 

Here is a simple C# program that uses the System.Drawing.Graphics class to upscale an image:


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

namespace ImageResizer
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "C:/path/to/image.jpg";
            int newWidth = 1200;
            int newHeight = 900;

            // Load the image from file
            Image originalImage = Image.FromFile(filePath);

            // Create a new bitmap with the new size
            Bitmap resizedImage = new Bitmap(newWidth, newHeight);

            // Set the interpolation mode to high quality
            resizedImage.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
            Graphics g = Graphics.FromImage(resizedImage);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // Draw the original image onto the bitmap with the new size
            g.DrawImage(originalImage, 0, 0, newWidth, newHeight);

            // Save the resized image to a new file
            resizedImage.Save("C:/path/to/resized_image.jpg");
        }
    }
}


This program loads an image from a file, creates a new bitmap with the specified width and height, and sets the interpolation mode to high quality. The original image is then drawn onto the bitmap with the new size using the high-quality interpolation mode. Finally, the resized image is saved to a new file.


Using a high-quality interpolation mode, such as InterpolationMode.HighQualityBicubic, can help to reduce the loss of quality when upscaling an image. However, it's important to remember that upscaling an image will always involve some loss of quality, and the resulting image may not be as clear or detailed as the original.

No comments:

Post a Comment

Microservices vs Monolithic Architecture

 Microservices vs Monolithic Architecture Here’s a clear side-by-side comparison between Microservices and Monolithic architectures — fro...