Wednesday 10 September 2008

Simple example how to resize images using C#

The other day I needed to resize images with a width greater than 500px to a new width of 250px, but also keeping the height in proportion to the width. Below is a snippet of code I used to achieve this.

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

string targetPath = "C:\\TestImage.jpg";
string destinationPath = "C:\\TestImage_New.jpg";
int newWidth = 200;
Image image = Image.FromFile(targetPath );
if (image.Width > 500)
{
    float percent = (float)newWidth / (float)image.Width;
int newHeight = (int)(image.Height * percent);
Bitmap bitmap = new Bitmap(newWidth, newHeight);
Graphics graphics = Graphics.FromImage((Image)bitmap);
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
graphics.Dispose();
image.Save(destinationPath);
} 

No comments: