Get Padded Aspect Ratio Thumbnail Image

I needed a GetThumbnail method which kept the aspect ratio of the original and also scaled the image with decent quality. There are several ways you can do this, I got a few examples here.

First, there is the Image.GetThumbnailImage() method which is pretty good if you just want to scale down the original image to a specific size, say 64 x 64:

    thumbnail = img.GetThumbnailImage(64, 64, Nothing, IntPtr.Zero)

But the problem with this method is the image get scewed and most people I think want to keep the aspect ratio. So if I want to scale down the original image by, say by 50%, and still keep the aspect ratio:

    Private Function GetAspectRatioThumbnail(ByVal img As Image, ByVal percent As Integer) As Image

        Dim ratio As Double = percent / 100

        Return img.GetThumbnailImage(img.Width * ratio, img.Height * ratio, Nothing, IntPtr.Zero)

    End Function

Very simple, yes, but if you've not been doing image manipulation before this could get you going I guess.

Now, I needed to fit a big image with unknown size into a fixed size area in a report, and this image area in the report streches the image to fit the bounds by itself. Not good. So I needed to both scale down the image, and "pad" it so it filled out the image area in the report. This little method helped me out here:

    Private Function GetPaddedAspectRatioThumbnail(ByVal img As Image, ByVal newSize As Size) As Image

        Dim thumb As New Bitmap(newSize.Width, newSize.Height)

        Dim ratio As Double

 

        If img.Width > img.Height Then

            ratio = newSize.Width / img.Width

        Else

            ratio = newSize.Height / img.Height

        End If

 

        Using g As Graphics = Graphics.FromImage(thumb)

            'if you want to tweak the quality of the drawing...

            g.InterpolationMode = InterpolationMode.HighQualityBicubic

            g.SmoothingMode = SmoothingMode.HighQuality

            g.PixelOffsetMode = PixelOffsetMode.HighQuality

            g.CompositingQuality = CompositingQuality.HighQuality

 

            g.DrawImage(img, 0, 0, CInt(img.Width * ratio), CInt(img.Height * ratio))

        End Using

 

        Return thumb

    End Function

You can tweek the quality of the image drawing as you see fit, it all depends on the size of the image, how much you need to scale it down and so on. I'm sure there are many other ways to do this, but it works for me.

 

No Comments