Question

Resizing an Image file in C#, from those wich are common used at least (bmp, jpg etc etc.)

I found many snippets but not a really complete one. So I'm gonna ask again so who comes here might use a complete file:

This just outputs a file with same width and height.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace PicResize
{
    class Program
    {
        static void Main(string[] args)
        {
            ResizeImage(0, 0, 200, 200);
        }

        public static void ResizeImage(int X1, int Y1, int Width, int Height)
        {

            string fileName = @"C:\testimage.jpg";
            using (Image image = Image.FromFile(fileName))
            {
                using (Graphics graphic = Graphics.FromImage(image))
                {
                    // Crop and resize the image.
                    Rectangle destination = new Rectangle(0, 0, Width, Height);
                    graphic.DrawImage(image, destination, X1, Y1, Width, Height, GraphicsUnit.Pixel);
                }
                image.Save(@"C:\testimagea.jpg");
            }
        }
    }
}

So, since there are no good examples around, How this works? What I need to fix here?

Thanks

Was it helpful?

Solution

You can do this:

        public void ResizeImage(string fileName, int width, int height)
        {
            using (Image image = Image.FromFile(fileName))
            {
                new Bitmap(image, width, height).Save(fileName);
            }
        }

If its a new file just replace with this or with a custom path of your choosing:

new Bitmap(image, width, height).Save(fileName.Insert(fileName.LastIndexOf('.'),"A"));

OTHER TIPS

The problem with your example code is that you are opening the image, and simple drawing on to that image, without actually changing the size.

What you can do is create a new Bitmap based on an original image and supply it with a new size. This function should work for you:

public void ResizeImage(string fileName, int width, int height)
{
    using (Image image = Image.FromFile(fileName))
    {
        using (Image newImage = new Bitmap(image, width, height))
        {
            //must dispose the original image to free up the file ready
            //for re-write, otherwise saving will throw an error
            image.Dispose();
            newImage.Save(fileName);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top