tags:

views:

287

answers:

5
+2  Q: 

Resize an Image C#

Hello there,

As Size, Width, Height are Get() properties for System.Drawing.Image,
How can I resize an Image object at run-time in C#.

Right now, I am just creating a new Image using:

Bitmap objBitmap = new Bitmap(objImage, new Size(227, 171));//objImage is the origional Image

Thank you!

+6  A: 

That would be the correct way of doing it.

astander
GetThumbnailImage is not a very reliable method (link1) (even if you do flip it twice)
UpTheCreek
Second link is much better.
UpTheCreek
A: 

Check this out.

gmcalab
+5  A: 

Create a new Bitmap in the new size, get a Graphics object from it, set InterpolationMode, and use DrawImage to paint the original image into the new one in the new size.

Lasse V. Karlsen
+1  A: 

in this question, you'll have some answers, including mine:

public Image resizeImage(int newWidth, int newHeight, string stPhotoPath)
 {
     Image imgPhoto = Image.FromFile(stPhotoPath); 

     int sourceWidth = imgPhoto.Width;
     int sourceHeight = imgPhoto.Height;

     //Consider vertical pics
    if (sourceWidth < sourceHeight)
    {
        int buff = newWidth;

        newWidth = newHeight;
        newHeight = buff;
    }

    int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
    float nPercent = 0, nPercentW = 0, nPercentH = 0;

    nPercentW = ((float)newWidth / (float)sourceWidth);
    nPercentH = ((float)newHeight / (float)sourceHeight);
    if (nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = System.Convert.ToInt16((newWidth -
                  (sourceWidth * nPercent)) / 2);
    }
    else
    {
        nPercent = nPercentW;
        destY = System.Convert.ToInt16((newHeight -
                  (sourceHeight * nPercent)) / 2);
    }

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);


    Bitmap bmPhoto = new Bitmap(newWidth, newHeight,
                  PixelFormat.Format24bppRgb);

    bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                 imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.Clear(Color.Black);
    grPhoto.InterpolationMode =
        InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto,
        new Rectangle(destX, destY, destWidth, destHeight),
        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();
    return bmPhoto;
}
Vinzz
A: 

You probably want to look at this stackoverflow question too:

http://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality

ninj