Click here to Skip to main content
15,885,141 members
Articles / Multimedia / GDI+
Tip/Trick

C#: Image resize, convert, and save

Rate me:
Please Sign up or sign in to vote.
4.87/5 (44 votes)
25 Feb 2013CPOL 240.8K   46   21
Resize an image and save in JPEG format using C#.

Introduction

If you work on a project that involves some image processing then you might come across where you need to do image resizing, converting etc.. This article will give you C# code snippet on how to resize an image to desired height and width without affecting the aspect ratio and save the image in JPEG format with the specified quality. Below given code handles the following

  • Resize a image to specified width and height 
  • Maintain the aspect ratio While resizing
  • Convert to RGB pixel format if image data is in any other format like YCCK, CMYK
  • Covert the image to JPEG format
  • Save the image in the given file path with the specified quality

Code

C#
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;

/// <summary>
/// Class contaning method to resize an image and save in JPEG format
/// </summary>
public class ImageHandler
{ 
    /// <summary>
    /// Method to resize, convert and save the image.
    /// </summary>
    /// <param name="image">Bitmap image.</param>
    /// <param name="maxWidth">resize width.</param>
    /// <param name="maxHeight">resize height.</param>
    /// <param name="quality">quality setting value.</param>
    /// <param name="filePath">file path.</param>      
    public void Save(Bitmap image, int maxWidth, int maxHeight, int quality, string filePath)
    {
        // Get the image's original width and height
        int originalWidth = image.Width;
        int originalHeight = image.Height;

        // To preserve the aspect ratio
        float ratioX = (float)maxWidth / (float)originalWidth;
        float ratioY = (float)maxHeight / (float)originalHeight;
        float ratio = Math.Min(ratioX, ratioY);

        // New width and height based on aspect ratio
        int newWidth = (int)(originalWidth * ratio);
        int newHeight = (int)(originalHeight * ratio);
 
        // Convert other formats (including CMYK) to RGB.
        Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);

        // Draws the image in the specified size with quality mode set to HighQuality
        using (Graphics graphics = Graphics.FromImage(newImage))
        {
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.DrawImage(image, 0, 0, newWidth, newHeight);
        }

        // Get an ImageCodecInfo object that represents the JPEG codec.
        ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Jpeg);

        // Create an Encoder object for the Quality parameter.
        Encoder encoder = Encoder.Quality;

        // Create an EncoderParameters object. 
        EncoderParameters encoderParameters = new EncoderParameters(1);

        // Save the image as a JPEG file with quality level.
        EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
        encoderParameters.Param[0] = encoderParameter;
        newImage.Save(filePath, imageCodecInfo, encoderParameters);
    }

    /// <summary>
    /// Method to get encoder infor for given image format.
    /// </summary>
    /// <param name="format">Image format</param>
    /// <returns>image codec info.</returns>
    private ImageCodecInfo GetEncoderInfo(ImageFormat format)
    {
        return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
    }
}

Hope it helps someone!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Ireland Ireland
Many years of experience in software design, development and architecture. Skilled in Microsoft .Net technology, Cloud computing, Solution Design, Software Architecture, Enterprise integration, Service Oriented and Microservices based Application Development. Currently, focusing on .Net Core, Web API, Microservices, Azure

Comments and Discussions

 
Questionsir please send the project of image compression Pin
Member 127192638-Nov-16 0:33
Member 127192638-Nov-16 0:33 
GeneralMy vote of 4 Pin
MRezaK13-Oct-16 0:29
MRezaK13-Oct-16 0:29 
Generalimage resize project Pin
Member 1271926314-Sep-16 0:42
Member 1271926314-Sep-16 0:42 
QuestionImage Crop Pin
Vipin Rawat11-Aug-15 7:32
professionalVipin Rawat11-Aug-15 7:32 
GeneralThanks Pin
Ronel Gonzales26-May-15 22:20
Ronel Gonzales26-May-15 22:20 
QuestionTransparent PNG Pin
martinrousev14-Apr-15 4:30
martinrousev14-Apr-15 4:30 
QuestionSource image size Pin
Ekugler23-Feb-15 3:00
Ekugler23-Feb-15 3:00 
AnswerThank you Pin
Frank Schwengsbier29-Jan-15 10:02
Frank Schwengsbier29-Jan-15 10:02 
GeneralRe: Thank you Pin
karinsue17-Jan-17 2:57
karinsue17-Jan-17 2:57 
QuestionError Pin
Member 1048118626-Jan-15 4:19
Member 1048118626-Jan-15 4:19 
AnswerRe: Error Pin
kyabroudi18-Dec-15 21:48
kyabroudi18-Dec-15 21:48 
QuestionGreat code Pin
Member 1037547025-Oct-14 2:29
Member 1037547025-Oct-14 2:29 
Question5 Stars Pin
RafaDomGal4-Oct-14 4:12
RafaDomGal4-Oct-14 4:12 
QuestionThank you Pin
nonintanon8-Aug-14 10:45
nonintanon8-Aug-14 10:45 
QuestionThank you Pin
Member 1083521621-May-14 9:14
Member 1083521621-May-14 9:14 
AnswerRe: Thank you Pin
John-ph21-May-14 20:12
John-ph21-May-14 20:12 
Questionfew questions Pin
mickhu3418-Mar-14 22:03
mickhu3418-Mar-14 22:03 
GeneralMy vote of 5 Pin
Pascualito27-Oct-13 12:40
professionalPascualito27-Oct-13 12:40 
Questionimage converting Pin
Wollaston24-Mar-13 22:07
Wollaston24-Mar-13 22:07 
AnswerRe: image converting Pin
JimBob SquarePants8-Jul-13 23:17
JimBob SquarePants8-Jul-13 23:17 
GeneralMy vote of 4 Pin
WhiteOsoBDN26-Feb-13 2:40
WhiteOsoBDN26-Feb-13 2:40 
Good

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.