Click here to Skip to main content
15,867,308 members
Articles / Multimedia / Image Processing

Resizing an Image On-The-Fly using .NET

Rate me:
Please Sign up or sign in to vote.
4.92/5 (69 votes)
5 May 2011CPOL2 min read 308.4K   82   39
How to resize an Image On-The-Fly using .NET

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#
// C#
using System.Drawing;
using System.Drawing.Drawing2D;
VB.NET
' Visual Basic
Imports System.Drawing
Imports System.Drawing.Drawing2D

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

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

}
VB.NET
' 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#
// 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;
}
VB.NET
' 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#
// C#
Image newImage = new Bitmap(newWidth, newHeight);
VB.NET
' 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#
// C#
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
    graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
VB.NET
' 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#
// 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;
}
VB.NET
' 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#
// 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);
VB.NET
' 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)


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWow. Thank you very much Pin
Member 106105753-May-20 16:40
Member 106105753-May-20 16:40 
Questionthanks Pin
jon bakari6-Aug-19 22:59
jon bakari6-Aug-19 22:59 
QuestionResizing an Image On-The-Fly using .NET Pin
KimbleGray18-Mar-18 1:34
KimbleGray18-Mar-18 1:34 
QuestionHow to Implement Pin
dkyle19-Jul-16 10:55
dkyle19-Jul-16 10:55 
QuestionThank you - you get my five stars Pin
timtocci30-Apr-16 18:42
timtocci30-Apr-16 18:42 
GeneralMy vote of 5 Pin
Ivan_FM23-Mar-16 1:28
professionalIvan_FM23-Mar-16 1:28 
PraiseHigh 5 on this.. Pin
Tino Fourie10-Nov-15 4:32
Tino Fourie10-Nov-15 4:32 
QuestionProblem with displaying image using a Smartphone Pin
DavidMills0216-Jun-15 1:02
DavidMills0216-Jun-15 1:02 
QuestionGet blank Form only Pin
Helium992-Jun-15 18:39
Helium992-Jun-15 18:39 
QuestionGreat Pin
N. Henrik Lauridsen21-May-15 1:14
N. Henrik Lauridsen21-May-15 1:14 
Questionwhat if my image is from the database ?? Pin
Member 1139871323-Jan-15 19:58
Member 1139871323-Jan-15 19:58 
hello to all.. what if my image is from the database ?? what should i do , i been working with this code but i can't find a way incorporate the image coming from the database with this code.. i hope u help me, thank you in advance Big Grin | :-D
AnswerRe: what if my image is from the database ?? Pin
Tino Fourie10-Nov-15 4:28
Tino Fourie10-Nov-15 4:28 
QuestionPerfect and awesome.. Pin
paddu2230-Dec-14 10:49
paddu2230-Dec-14 10:49 
GeneralGreat article Pin
a5aa-1024-055224-Sep-14 16:41
a5aa-1024-055224-Sep-14 16:41 
GeneralGood article Pin
samkamiru5-Mar-14 9:25
samkamiru5-Mar-14 9:25 
QuestionHow to return values from your method Pin
Member 1025370110-Sep-13 16:00
professionalMember 1025370110-Sep-13 16:00 
AnswerRe: How to return values from your method Pin
gdshukla4-Aug-15 22:54
gdshukla4-Aug-15 22:54 
GeneralMy vote of 5 Pin
CyberAngel22-Jul-13 3:51
CyberAngel22-Jul-13 3:51 
QuestionExcellent Pin
ak1619-Jul-13 5:40
ak1619-Jul-13 5:40 
GeneralMy vote of 5 Pin
SeraphimFoa27-Feb-13 23:40
SeraphimFoa27-Feb-13 23:40 
GeneralMy vote of 5 Pin
vb-4-me18-Feb-13 5:13
vb-4-me18-Feb-13 5:13 
GeneralMy vote of 5 Pin
Johan Hakkesteegt17-Dec-12 3:19
Johan Hakkesteegt17-Dec-12 3:19 
QuestionA suggestion for improving the display in web apps Pin
yaron1115-Nov-12 8:33
yaron1115-Nov-12 8:33 
GeneralMy vote of 5 Pin
Noel Buenaventura13-Nov-12 20:50
Noel Buenaventura13-Nov-12 20:50 
GeneralMy vote of 5 Pin
John Mikkelä12-Nov-12 7:02
John Mikkelä12-Nov-12 7:02 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.