Click here to Skip to main content
Click here to Skip to main content

Resizing an Image On-The-Fly using .NET

By , 5 May 2011
 

The other day, I was given the requirement to be able to dynamically resize a JPEG image server-side before rendering it down to the browser, thus reducing unnecessary bandwidth usage between the server and the client.

Clearly, it would be more efficient to store the original image in the different sizes required, as resizing the images on-the-fly would put an unnecessary additional load on the server, however in this case, it wasn't an option.

Firstly, we are going to need the System.Drawing and System.Drawing.Drawing2D namespaces:

// C#
using System.Drawing;
using System.Drawing.Drawing2D;
' Visual Basic
Imports System.Drawing
Imports System.Drawing.Drawing2D

Secondly, the signature for our method which is going to do the resizing:

// C#
public static Image ResizeImage(Image image, Size size, bool preserveAspectRatio = true)
{

}
' Visual Basic
Public Shared Function ResizeImage(ByVal image As Image, _
  ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True) As Image

End Function

As you can see, the method takes two mandatory parameters: the image to be resized and the new size it is to be resized to. An optional third parameter specifies whether to preserve the image's original aspect ratio.

If we are not going to preserve the aspect ratio of the original image, then we simply set the height and width of the new image accordingly. However, if we do wish to preserve the aspect ratio, then the situation is a little more complex: Firstly, we need to calculate the percentage difference, in each axis (height and width), between the original image and the desired size. Then we use whichever difference is the smaller to calculate the new height and width of the new image:

// C#
int newWidth;
int newHeight;
if (preserveAspectRatio)
{
    int originalWidth = image.Width;
    int originalHeight = image.Height;
    float percentWidth = (float)size.Width / (float)originalWidth;
    float percentHeight = (float)size.Height / (float)originalHeight;
    float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
    newWidth = (int)(originalWidth * percent);
    newHeight = (int)(originalHeight * percent);
}
else
{
    newWidth = size.Width;
    newHeight = size.Height;
}
' Visual Basic
Dim newWidth As Integer
Dim newHeight As Integer
If preserveAspectRatio Then
    Dim originalWidth As Integer = image.Width
    Dim originalHeight As Integer = image.Height
    Dim percentWidth As Single = CSng(size.Width) / CSng(originalWidth)
    Dim percentHeight As Single = CSng(size.Height) / CSng(originalHeight)
    Dim percent As Single = If(percentHeight < percentWidth, percentHeight, percentWidth)
    newWidth = CInt(originalWidth * percent)
    newHeight = CInt(originalHeight * percent)
Else
    newWidth = size.Width
    newHeight = size.Height
End If

Next, we create a blank bitmap using our new dimensions:

// C#
Image newImage = new Bitmap(newWidth, newHeight);
' Visual Basic
Dim newImage As Image = New Bitmap(newWidth, newHeight)

Finally, we use the graphics handle of the new bitmap to draw the original image onto our new bitmap and return it:

// C#
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
    graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
' Visual Basic
Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
    graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
    graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight)
End Using
Return newImage

You can experiment with the interpolation mode to vary the quality of the resized image. Personally, I found HighQualityBicubic to give the best results. The code for the complete method is as follows:

// C#
public static Image ResizeImage(Image image, Size size, 
	bool preserveAspectRatio = true)
{
    int newWidth;
    int newHeight;
    if (preserveAspectRatio)
    {
        int originalWidth = image.Width;
        int originalHeight = image.Height;
        float percentWidth = (float)size.Width / (float)originalWidth;
        float percentHeight = (float)size.Height / (float)originalHeight;
        float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
        newWidth = (int)(originalWidth * percent);
        newHeight = (int)(originalHeight * percent);
    }
    else
    {
        newWidth = size.Width;
        newHeight = size.Height;
    }
    Image newImage = new Bitmap(newWidth, newHeight);
    using (Graphics graphicsHandle = Graphics.FromImage(newImage))
    {
        graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
    }
    return newImage;
}
' Visual Basic
Public Shared Function ResizeImage(ByVal image As Image, _
  ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True) As Image
    Dim newWidth As Integer
    Dim newHeight As Integer
    If preserveAspectRatio Then
        Dim originalWidth As Integer = image.Width
        Dim originalHeight As Integer = image.Height
        Dim percentWidth As Single = CSng(size.Width) / CSng(originalWidth)
        Dim percentHeight As Single = CSng(size.Height) / CSng(originalHeight)
        Dim percent As Single = If(percentHeight < percentWidth, 
				percentHeight, percentWidth)
        newWidth = CInt(originalWidth * percent)
        newHeight = CInt(originalHeight * percent)
    Else
        newWidth = size.Width
        newHeight = size.Height
    End If
    Dim newImage As Image = New Bitmap(newWidth, newHeight)
    Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
        graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
        graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight)
    End Using
    Return newImage
End Function

We can then call the method at an appropriate point to resize the image. In this example, I simply read the original image from disk and then save the resized image to a MemoryStream for use later in the application:

// C#
Image original = Image.FromFile(@"C:\path\to\some.jpg");
Image resized = ResizeImage(original, new Size(1024, 768));
MemoryStream memStream = new MemoryStream();
resized.Save(memStream, ImageFormat.Jpeg);
' Visual Basic
Dim original As Image = Image.FromFile("C:\path\to\some.jpg")
Dim resized As Image = ResizeImage(original, New Size(1024, 768))
Dim memStream As MemoryStream = New MemoryStream()
resized.Save(memStream, ImageFormat.Jpeg)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

MBigglesworth79
Web Developer
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberSeraphimFoa27 Feb '13 - 23:40 
Very precise and rich of content
GeneralMy vote of 5memberDavid from Florida18 Feb '13 - 5:13 
This is an excellent topic, the code works well, there's a good description, and it's in both languages.
GeneralMy vote of 5memberJohan Hakkesteegt17 Dec '12 - 3:19 
Just what the doctor ordered !
QuestionA suggestion for improving the display in web appsmemberyaron1115 Nov '12 - 8:33 
Hi, I have used your code and it helps, thanks!!!
 
I changed this line:
float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
to this
float percent = percentHeight > percentWidth ? percentHeight : percentWidth;
 
I create a div with a fixed width & height + overflow:hidden, and put an img tag inside, which is resized.
The result is that the bigger dimension (width or height) is cropped, but the part which is displayed looks good
 
thanks
GeneralMy vote of 5memberNoel Buenaventura13 Nov '12 - 20:50 
Nice Job!!!
GeneralMy vote of 5memberJohn Mikkelä12 Nov '12 - 7:02 
Excellent - Well done...
Buggreat but one small detail... RESIZE PRECISIONmembereniro95824 Oct '12 - 6:49 
if you do:
newWidth = (int)(originalWidth * percent);
newHeight = (int)(originalHeight * percent);
the casting will remove the decimal place not round it (eg 224.9 => 224)
 
better to use:
newWidth = Convert.ToInt32(originalWidth * percent);
newHeight = Convert.ToInt32(originalHeight * percent);
(224.9 => 225)
GeneralGreat!memberJuan R. Huertas20 Aug '12 - 22:05 
It works perfect! Thank you!Thumbs Up | :thumbsup:
GeneralExcellentmemberfchateau24 Jul '12 - 22:27 
Excellent -- Well done.
GeneralMy vote of 5memberWalter Lippens18 May '12 - 3:33 
Works like a charm
GeneralMy vote of 5membertrx123 Mar '12 - 4:09 
Straightforward...copy paste and it just works.
GeneralMy vote of 5memberkiran dangar5 Oct '11 - 2:10 
nice
GeneralMy vote of 5mvpMd. Marufuzzaman15 Jun '11 - 20:00 
Excellent
GeneralNice one!memberAnt210026 May '11 - 9:53 
Thanks for this, much needed Smile | :)
Bookmarked, 5 stars!
Check out my unit conversion software for Windows!

GeneralMy vote of 5memberKim Togo9 May '11 - 21:59 
Bookmarked, good one.
GeneralJPEG Quality...memberDrew Stainton5 May '11 - 7:29 
One of the things I rarely see mentioned in these types of articles is how to set the quality of JPEG images. Depending on the source image, the default quality can show quite a few artifacts. That might be something to include in your article, even if it's only a reference to this[^].
 
Cheers,
Drew.
GeneralRe: JPEG Quality...memberMBigglesworth795 May '11 - 21:57 
Good point and certainly would be a consideration where image quality is a key requirement.
 
Thanks for the link! Smile | :)
GeneralNice, simple and cleanmemberMario Majcica5 May '11 - 2:45 
Bravo!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 5 May 2011
Article Copyright 2011 by MBigglesworth79
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid