Resizing an image using C #

Images that are fresh from digital cameras often exceed the size of 2-3 MB, which makes it difficult to transfer it by e-mail and other methods. This requires resizing the image (in terms of file size, not height or width). Just like MS Paint, offering image resizing features. I'm not good at image file theories. I would be grateful if someone could point me to the following sources of information:

  • Image theory (how various image formats work jpeg, png, tiff, etc.).

  • How does the image get worse when resized? Whether there is a

  • Are there any .Net libraries (I use 4.0) for this? If not, can I use any library using COM compatibility?

Many thanks,

+5
source share
3 answers

Image resizing is a feature built right into the .NET framework. There are several different approaches:

  • Gdi +
  • Wic
  • WPF

Here is a good blog post that describes the differences between them.

Here is an example with GDI +:

public void Resize(string imageFile, string outputFile, double scaleFactor)
{
    using (var srcImage = Image.FromFile(imageFile))
    {
        var newWidth = (int)(srcImage.Width * scaleFactor);
        var newHeight = (int)(srcImage.Height * scaleFactor);
        using (var newImage = new Bitmap(newWidth, newHeight))
        using (var graphics = Graphics.FromImage(newImage))
        {
            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
            newImage.Save(outputFile);
        }
    }
}
+24
source

I used the example of Darin Dimitrova. The image was oversized and took up a lot of disk space (from 1.5 MB to 17 MB or so).

This is due to a small error in the last line of code.

The function below will save the image as a bitmap (huge image size).

newImage.Save(outputFile)

The correct function should be:

newImage.Save(outputFile, ImageFormat.Jpeg);
+7
source

Imageresizer works well. http://imageresizing.net/

+2
source

All Articles