Resize an Image and keep it’s proportion

Posted: 11/22/2014


You want to resize an Image (System.Drawing.Image or an object that inherits from it like Bitmap) and you want to keep the proportions the same. You can do this by determining the ratio by setting the max width and height that you would want to use. I found exactly what I wanted to do in a blog post located at the link below and converted it to VB.Net. I'll include the VB.Net converted version here and provide a link to the C# version.


        ''' <summary>
        ''' Resizes an image keeping the proportion correct.  This returns a new Image, the passed in image can
        ''' be disposed off afterwards.
        ''' </summary>
        ''' <param name="sourceImage"></param>
        ''' <param name="maxWidth"></param>
        ''' <param name="maxHeight"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function ResizeImageInProportion(sourceImage As Image, maxWidth As Integer, maxHeight As Integer) As Image
            ' Determine which ratio is greater, the width or height, and use this to calculate the new width and height
            ' Effectually constrains the proportions of the resized image to the proportions of the original.
            Dim xRatio As Double = CDbl(sourceImage.Width) / maxWidth
            Dim yRatio As Double = CDbl(sourceImage.Height) / maxHeight
            Dim ratioToResizeImage As Double = Math.Max(xRatio, yRatio)
            Dim newWidth As Integer = CInt(Math.Floor(sourceImage.Width / ratioToResizeImage))
            Dim newHeight As Integer = CInt(Math.Floor(sourceImage.Height / ratioToResizeImage))

            ' Create new image canvas -- use maxWidth and maxHeight in this function call if you wish to set the exact
            ' dimensions of the output image.
            Dim newImage As New Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb)

            ' Render the new image, using a graphic object
            Using newGraphic As Graphics = Graphics.FromImage(newImage)
                ' Set the background color to be transparent (can change this to any color)

                ' Set the method of scaling to use -- HighQualityBicubic is said to have the best quality
                newGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic

                ' Apply the transformation onto the new graphic
                Dim sourceDimensions As New Rectangle(0, 0, sourceImage.Width, sourceImage.Height)
                Dim destinationDimensions As New Rectangle(0, 0, newWidth, newHeight)
                newGraphic.DrawImage(sourceImage, destinationDimensions, sourceDimensions, GraphicsUnit.Pixel)
            End Using

            ' Image has been modified by all the references to it's related graphic above. Return changes.
            Return newImage
        End Function

C# Version