Sandip's Programming Zen

An attempt to share tech/coding experiences

C# : Resize image in Picture Box for Best fit

with 3 comments

Got a useful piece of here which I have implemented in following way to make a image preview form.

private void frmPreview_Load(object sender, EventArgs e)
{
try
{

pboxMain.Image = Image.FromFile(_imagePath);
pboxMain.Tag = Image.FromFile(_imagePath);
}
catch(Exception ex)
{
Log.Error(ex);
}
}

private void btFit_Click(object sender, EventArgs e)
{

if (btFit.Text == “Fit to Screen”)
{
handleFitToWindow(true);
btFit.Text = “Actual Size”;
}
else
{
handleFitToWindow(false);
btFit.Text = “Fit to Screen”;
}

}

private void handleFitToWindow(bool doFit)
{
try
{
/* Don’t perform any operation if no image is loaded. */
if (this.pboxMain.Tag != null)
{
if (doFit)  /* We’re fitting it to the window, and centering it. */
{
/* Create a temporary Image.

* Always work from the original image, stored in the Tag.
*/

Image tempImage = (Image)this.pboxMain.Tag;

/* Calculate the dimensions necessary for an image to fit. */
Size fitImageSize = this.getScaledImageDimensions(
tempImage.Width, tempImage.Height, this.pboxMain.Width, this.pboxMain.Height);

/* Create a new Bitmap from the original image with the new dimensions.

* The constructor for the Bitmap object automatically scales as necessary.
*/

Bitmap imgOutput = new Bitmap(tempImage, fitImageSize.Width, fitImageSize.Height);

/* Clear any existing image in the PictureBox. */
this.pboxMain.Image = null;

/* When fitting the image to the window, we want to keep it centered. */
this.pboxMain.SizeMode = PictureBoxSizeMode.CenterImage;

/* Finally, set the Image property to point to the new, resized image. */
this.pboxMain.Image = imgOutput;
}

else  /* Restore the image to its original size */
{
/* Clear any existing image int he PictureBox. */
this.pboxMain.Image = null;

/* Set the resize more to Normal; this will place the image

* in the upper left-hand corner, clipping the image as required.
*/

this.pboxMain.SizeMode = PictureBoxSizeMode.Normal;

/* Finally, set the Image property to point to the original image. */
this.pboxMain.Image = (Image)this.pboxMain.Tag;
}
}
}
catch (System.Exception e)
{
Console.WriteLine(e);
}
}

private Size getScaledImageDimensions(
int currentImageWidth,
int currentImageHeight,
int desiredImageWidth,
int desiredImageHeight)
{
/* First, we must calculate a multiplier that will be used

* to get the dimensions of the new, scaled image.
*/

double scaleImageMultiplier = 0;

/* This multiplier is defined as the ratio of the

* Desired Dimension to the Current Dimension.
* Specifically which dimension is used depends on the larger
* dimension of the image, as this will be the constraining dimension
* when we fit to the window.
*/

/* Determine if Image is Portrait or Landscape. */
if (currentImageHeight > currentImageWidth)    /* Image is Portrait */
{
/* Calculate the multiplier based on the heights. */
if (desiredImageHeight > desiredImageWidth)
{
scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
}

else
{
scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
}
}

else /* Image is Landscape */
{
/* Calculate the multiplier based on the widths. */
if (desiredImageHeight >= desiredImageWidth)
{
scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
}

else
{
scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
}
}

/* Generate and return the new scaled dimensions.

* Essentially, we multiply each dimension of the original image
* by the multiplier calculated above to yield the dimensions
* of the scaled image. The scaled image can be larger or smaller
* than the original.
*/

return new Size(
(int)(currentImageWidth * scaleImageMultiplier),
(int)(currentImageHeight * scaleImageMultiplier));
}

}

About these ads

Written by Sandip

September 17, 2009 at 11:27 am

Posted in .Net, Programming

Tagged with ,

3 Responses

Subscribe to comments with RSS.

  1. Cool blog!

    Rock Tops Granite

    Rocks Tops

    December 28, 2009 at 7:05 pm

  2. Correct line with:
    if (desiredImageHeight > desiredImageWidth)
    in the /* Image is Landscape */

    it should be >=

    if (desiredImageHeight >= desiredImageWidth)

    3mode

    January 10, 2010 at 7:30 pm

    • Thanks, its corrected.

      Sandip

      February 12, 2010 at 9:23 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: