Search code examples
c#imageresizegraphic

Resizing an image with c#


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


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"));