Home > ASP.NET, C#, Graphics, Programming, Tips & Tricks > Image Resizing in C#

Image Resizing in C#

Once upon a time there were objects like ASPJeg which made it possible to manipulate images files – resize, convert and much more…

Lucky for us those times are gone and now we have a great framework called .NET, so why not use it ?

Some Image extension methods that will make your life easier.

    public static class ImageExtensionMethods
    {

        static private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
        }

        public static void SaveAsJpeg(this Image Img, string FileName, Int64 Quality)
        {
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            Encoder QualityEncoder = Encoder.Quality;

            using (EncoderParameters EP = new EncoderParameters(1))
            {
                using (EncoderParameter QualityEncoderParameter = new EncoderParameter(QualityEncoder, Quality))
                {
                    EP.Param[0] = QualityEncoderParameter;
                    Img.Save(FileName, jgpEncoder, EP);
                }
            }
        }

        public static void SaveAsGif(this Image Img, string FileName, Int64 Quality)
        {
            ImageCodecInfo gifEncoder = GetEncoder(ImageFormat.Gif);
            Encoder QualityEncoder = Encoder.Quality;

            using (EncoderParameters EP = new EncoderParameters(1))
            {
                using (EncoderParameter QualityEncoderParameter = new EncoderParameter(QualityEncoder, Quality))
                {
                    EP.Param[0] = QualityEncoderParameter;
                    Img.Save(FileName, gifEncoder, EP);
                }
            }
        }

        public static Image Resize(this Image Img, int Width, int Height, InterpolationMode InterpolationMode)
        {
            Image CropedImage = new Bitmap(Width, Height);
            using (Graphics G = Graphics.FromImage(CropedImage))
            {
                G.SmoothingMode = SmoothingMode.HighQuality;
                G.InterpolationMode = InterpolationMode;
                G.PixelOffsetMode = PixelOffsetMode.HighQuality;
                G.DrawImage(Img, 0, 0, Width, Height);
            }

            return CropedImage;
        }

        public static Image Resize(this Image Img, int Width, int Height)
        {
            return Img.Resize(Width, Height, InterpolationMode.HighQualityBicubic);
        }

        private static Rectangle EnsureAspectRatio(this Image Image, int Width, int Height)
        {
            float AspectRatio = Width / (float)Height;
            float CalculatedWidth = Image.Width, CalculatedHeight = Image.Height;

            if (Image.Width >= Image.Height)
            {
                if (Width > Height)
                {
                    CalculatedHeight = Image.Width / AspectRatio;
                    if (CalculatedHeight > Image.Height)
                    {
                        CalculatedHeight = Image.Height;
                        CalculatedWidth = CalculatedHeight * AspectRatio;
                    }
                }
                else
                {
                    CalculatedWidth = Image.Height * AspectRatio;
                    if (CalculatedWidth > Image.Width)
                    {
                        CalculatedWidth = Image.Width;
                        CalculatedHeight = CalculatedWidth / AspectRatio;
                    }
                }
            }
            else
            {
                if (Width < Height)
                {
                    CalculatedHeight = Image.Width / AspectRatio;
                    if (CalculatedHeight > Image.Height)
                    {
                        CalculatedHeight = Image.Height;
                        CalculatedWidth = CalculatedHeight * AspectRatio;
                    }
                }
                else
                {
                    CalculatedWidth = Image.Height * AspectRatio;
                    if (CalculatedWidth > Image.Width)
                    {
                        CalculatedWidth = Image.Width;
                        CalculatedHeight = CalculatedWidth / AspectRatio;
                    }
                }
            }
            return Rectangle.Ceiling(new RectangleF((Image.Width - CalculatedWidth) / 2, 0, CalculatedWidth, CalculatedHeight));
        }

        public static Image ResizeToCanvas(this Image Img, int Width, int Height, out Rectangle CropRectangle)
        {
            return Img.ResizeToCanvas(Width, Height, InterpolationMode.HighQualityBicubic, out CropRectangle);
        }

        public static Image ResizeToCanvas(this Image Img, int Width, int Height,InterpolationMode InterpolationMode, out Rectangle CropRectangle)
        {
            CropRectangle = EnsureAspectRatio(Image, Width, Height);
            Image CropedImage = new Bitmap(Width, Height);

            using (Graphics G = Graphics.FromImage(CropedImage))
            {
                G.SmoothingMode = SmoothingMode.HighQuality;
                G.InterpolationMode = InterpolationMode;
                G.PixelOffsetMode = PixelOffsetMode.HighQuality;
                G.DrawImage(Img, new Rectangle(0, 0, Width, Height), CropRectangle, GraphicsUnit.Pixel);
            }

            return CropedImage;
        }

        public static Image ResizeToCanvas(this Image Img, int Width, int Height, RectangleF CR)
        {
            return Img.ResizeToCanvas(Width, Height, InterpolationMode.HighQualityBicubic, CR);
        }

        public static Image ResizeToCanvas(this Image Img, int Width, int Height, InterpolationMode InterpolationMode, RectangleF CR)
        {
            Image CropedImage = new Bitmap(Width, Height);
            using (Graphics G = Graphics.FromImage(CropedImage))
            {
                G.SmoothingMode = SmoothingMode.HighQuality;
                G.InterpolationMode = InterpolationMode;
                G.PixelOffsetMode = PixelOffsetMode.HighQuality;
                G.DrawImage(Img, new Rectangle(0, 0, Width, Height), CR, GraphicsUnit.Pixel);
            }

            return CropedImage;
        }

    }
VN:F [1.9.13_1145]
Rating: 5.0/5 (4 votes cast)
Image Resizing in C#, 5.0 out of 5 based on 4 ratings

  1. Tony Brand
    August 19th, 2009 at 18:49 | #1

    Hi

    Thanks for the example. I just wanted to get the image resizing working, and wrote the following function after seeing your code:

    public System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int Width, int Height, InterpolationMode InterpolationMode)
    {
    System.Drawing.Image CropedImage = new Bitmap(Width, Height);
    using (Graphics G = Graphics.FromImage(CropedImage))
    {
    G.SmoothingMode = SmoothingMode.HighQuality;
    G.InterpolationMode = InterpolationMode;
    G.PixelOffsetMode = PixelOffsetMode.HighQuality;
    G.DrawImage(originalImage, 0, 0, Width, Height);
    }

    return CropedImage;
    }

    I then save the returned image, e.g.: ResizeImage(image).Save(“C:/Documents/Images/ResizedImage.jpg”);

    I am finding though that the saved image is somehow not valid, it doesn’t not open in Internet Explorer, or Fireworks (get error message: “Could not open the file. Unknown file type”), although it does open and looks fine in FireFox and Safari.

    I have had the same problem trying a number of examples using the Graphics.DrawImage() method. Do you know anything about this problem?

    Thanks again, any help would be appreciated

    VA:F [1.9.13_1145]
    Rating: 3.0/5 (2 votes cast)
  2. Tony Brand
    August 19th, 2009 at 18:50 | #2

    Hi

    Thanks for the example. I just wanted to get the image resizing working, and wrote the following function after seeing your code:

    public System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int Width, int Height, InterpolationMode InterpolationMode)
    {
    System.Drawing.Image CropedImage = new Bitmap(Width, Height);
    using (Graphics G = Graphics.FromImage(CropedImage))
    {
    G.SmoothingMode = SmoothingMode.HighQuality;
    G.InterpolationMode = InterpolationMode;
    G.PixelOffsetMode = PixelOffsetMode.HighQuality;
    G.DrawImage(originalImage, 0, 0, Width, Height);
    }

    return CropedImage;
    }

    I then save the returned image, e.g.: ResizeImage(image).Save(“C:/Documents/Images/ResizedImage.jpg”);

    I am finding though that the saved image is somehow not valid, it does not open in Internet Explorer, or Fireworks (get error message: “Could not open the file. Unknown file type”), although it does open and looks fine in FireFox and Safari.

    I have had the same problem trying a number of examples using the Graphics.DrawImage() method. Do you know anything about this problem? Perhaps there are some extra settings that need to be made?

    Thanks again, any help would be appreciated

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  3. jo0ls
    October 9th, 2009 at 11:25 | #3

    Encoder.Quality doesn’t do anything with Gifs.

    VA:F [1.9.13_1145]
    Rating: 4.5/5 (2 votes cast)
  4. February 2nd, 2010 at 15:48 | #4

    This extender is really useful, thanks.

    I’ve been struggling with resizing and maintaining the image quality while using the .net framework, and nearly resorted to a library that was a bit overkill.

    Glad I found this in time :)

    VA:F [1.9.13_1145]
    Rating: 3.0/5 (2 votes cast)
  5. May 3rd, 2010 at 05:01 | #5

    Thank you, excellent

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  6. Matjaz
    May 11th, 2010 at 14:27 | #6

    Thanks, i spent a lot of time searching for some good code to do image resize.

    I have only one question:
    What is Int64 Quality attribute for saving images. Which value should i set for this parameter?

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  7. May 11th, 2010 at 21:10 | #7

    @Matjaz
    The Quality category specifies the level of compression for an image. When used to construct an EncoderParameter, the range of useful values for the quality category is from 0 to 100. The lower the number specified, the higher the compression and therefore the lower the quality of the image. Zero would give you the lowest quality image and 100 the highest.

    MSDN – Encoder.Quality

    VN:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  8. George
    April 21st, 2011 at 13:25 | #8

    @Matjaz: hi frnd, Change Int64 to System.Int64

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  9. George
    April 21st, 2011 at 13:50 | #9

    System.Drawing.Image test_image = System.Drawing.Image.FromFile(Server.MapPath(“images.jpg”));

    System.Drawing.Image final_image = test_image.Resize(500, 500);

    final_image.Save(Server.MapPath(“images/resized_image.jpg”));

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  10. George
    April 21st, 2011 at 13:50 | #10

    @Tony Brand

    System.Drawing.Image test_image = System.Drawing.Image.FromFile(Server.MapPath(“images.jpg”));

    System.Drawing.Image final_image = test_image.Resize(500, 500);

    final_image.Save(Server.MapPath(“images/resized_image.jpg”));

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  11. George
    April 21st, 2011 at 13:52 | #11

    @Tony Brand

    System.Drawing.Image test_image = System.Drawing.Image.FromFile(Server.MapPath(“images.jpg”));
    System.Drawing.Image final_image = test_image.Resize(500, 500);
    final_image.Save(Server.MapPath(“images/resized_image.jpg”));

    VA:F [1.9.13_1145]
    Rating: 0.0/5 (0 votes cast)
  1. No trackbacks yet.

Subscribe without commenting

SEO Powered by Platinum SEO from Techblissonline
watch free movies