12

Using C# how can I resize a jpeg image? A code sample would be great.

Saahithyan Vigneswaran
  • 6,841
  • 3
  • 35
  • 45
Steven W
  • 129
  • 1
  • 1
  • 3

5 Answers5

5

I'm using this:

 public static void ResizeJpg(string path, int nWidth, int nHeight)
    {
        using (var result = new Bitmap(nWidth, nHeight))
        {
            using (var input = new Bitmap(path))
            {
                using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
                {
                    g.DrawImage(input, 0, 0, nWidth, nHeight);
                }
            }

            var ici = ImageCodecInfo.GetImageEncoders().FirstOrDefault(ie => ie.MimeType == "image/jpeg");
            var eps = new EncoderParameters(1);
            eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
            result.Save(path, ici, eps);
        }
    }
Tico Fortes
  • 499
  • 4
  • 6
  • This works, but be careful - it shrinks my 1920x1080 image to 960x540... but the file size of the smaller version is 3x the full version. Investigating a fix to that... – Morvael Sep 17 '19 at 14:41
  • @Morvael That's because of that '100L' near the end: the image is saved at 100% quality (70-80% range is more normal). Even reducing it to 90% should give a drastic reduction in size - the last few percent really inflates the size. – AnorZaken Nov 27 '19 at 09:34
  • Microsoft recommends to get JPEG Codec by `FormatId`: ImageCodecInfo _jpegCodecInfo = ImageCodecInfo.GetImageEncoders().First(v => v.FormatID == ImageFormat.Jpeg.Guid) – Sergei Zinovyev Sep 25 '20 at 00:34
3

Good free resize filter and example code.

http://code.google.com/p/zrlabs-yael/

    private void MakeResizedImage(string fromFile, string toFile, int maxWidth, int maxHeight)
    {
        int width;
        int height;

        using (System.Drawing.Image image = System.Drawing.Image.FromFile(fromFile))
        {
            DetermineResizeRatio(maxWidth, maxHeight, image.Width, image.Height, out width, out height);

            using (System.Drawing.Image thumbnailImage = image.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
            {
                if (image.Width < thumbnailImage.Width && image.Height < thumbnailImage.Height)
                    File.Copy(fromFile, toFile);
                else
                {
                    ImageCodecInfo ec = GetCodecInfo();
                    EncoderParameters parms = new EncoderParameters(1);
                    parms.Param[0] = new EncoderParameter(Encoder.Compression, 40);

                    ZRLabs.Yael.BasicFilters.ResizeFilter rf = new ZRLabs.Yael.BasicFilters.ResizeFilter();
                    //rf.KeepAspectRatio = true;
                    rf.Height = height;
                    rf.Width = width;

                    System.Drawing.Image img = rf.ExecuteFilter(System.Drawing.Image.FromFile(fromFile));
                    img.Save(toFile, ec, parms);
                }
            }
        }
    }
keithwarren7
  • 14,094
  • 8
  • 53
  • 74
  • 2
    Notice that this piece of code is not enough, you must add reference to the project (last change was on Nov 6, 2006) – itsho Nov 21 '14 at 05:41
2

Nice example.

public static Image ResizeImage(Image sourceImage, int maxWidth, int maxHeight)
{
    // Determine which ratio is greater, the width or height, and use
    // this to calculate the new width and height. Effectually constrains
    // the proportions of the resized image to the proportions of the original.
    double xRatio = (double)sourceImage.Width / maxWidth;
    double yRatio = (double)sourceImage.Height / maxHeight;
    double ratioToResizeImage = Math.Max(xRatio, yRatio);
    int newWidth = (int)Math.Floor(sourceImage.Width / ratioToResizeImage);
    int newHeight = (int)Math.Floor(sourceImage.Height / ratioToResizeImage);

    // Create new image canvas -- use maxWidth and maxHeight in this function call if you wish
    // to set the exact dimensions of the output image.
    Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);

    // Render the new image, using a graphic object
    using (Graphics newGraphic = Graphics.FromImage(newImage))
    {
        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            newGraphic.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
        }

        // Set the background color to be transparent (can change this to any color)
        newGraphic.Clear(Color.Transparent);

        // Set the method of scaling to use -- HighQualityBicubic is said to have the best quality
        newGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

        // Apply the transformation onto the new graphic
        Rectangle sourceDimensions = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
        Rectangle destinationDimensions = new Rectangle(0, 0, newWidth, newHeight);
        newGraphic.DrawImage(sourceImage, destinationDimensions, sourceDimensions, GraphicsUnit.Pixel);
    }

    // Image has been modified by all the references to it's related graphic above. Return changes.
    return newImage;
}

Source : http://mattmeisinger.com/resize-image-c-sharp

André Leal
  • 60
  • 1
  • 6
  • Specifying a `WrapMode` like in LucidObscurity's answer gives you a better result. You may want to add that to your code. – Andrew Oct 16 '15 at 04:46
2

C# (or rather: the .NET framework) itself doesn't offer such capability, but it does offer you Bitmap from System.Drawing to easily access the raw pixel data of various picture formats. For the rest, see http://en.wikipedia.org/wiki/Image_scaling

1

ImageMagick should be the best way. Easy and reliable.

using (var image = new MagickImage(imgfilebuf))
{
    image.Resize(len, len);
    image.Strip();
    using MemoryStream ms = new MemoryStream();
    image.Write(ms);
    return ms.ToArray();
}
Danger Saints
  • 507
  • 1
  • 4
  • 10