Question

I need generate thumbnails for a bunch of jpegs (200,000+) but I want to make sure all of my thumbs have a equal height and width. However, I don't want to change the proportions of the image so I need to add empty space to the shorter dimension to "square it up". The empty space's background color is variable.

Here's the code snippet I'm using to generate the thumbs. What's the best way to do the squaring?

     Dim imgDest As System.Drawing.Bitmap = New Bitmap(ScaleWidth, ScaleHeight)
     imgDest.SetResolution(TARGET_RESOLUTION, TARGET_RESOLUTION)  
     Dim grDest As Graphics = Graphics.FromImage(imgDest)

     grDest.DrawImage(SourceImage, 0, 0, imgDest.Width, imgDest.Height)
Was it helpful?

Solution

How about this. Maybe you should draw a black (or whichever color) rectangle on the Bitmap first.

And then when you are placing the resized image, just calculate the placement of the image based on whichever dimension is shorter, and then move that dimension by half the difference (and keep the other on 0).

Wouldn't that work?

OTHER TIPS

Like Vaibhav said, first paint the entire thumbnail area with black. This will be simpler than first fitting the image into the thumbnail and then determining which rectangles to paint black to achieve pillarboxing or letterboxing.

Pseudo-code for a general solution to fit an imageWidth x imageHeight image into a thumbWidth x thumbHeight (doesn't have to be a square) area:

imageRatio = imageWidth / imageHeight;
thumbRatio = thumbWidth / thumbHeight;

zoomFactor = imageRatio >= thumbRatio
    ? thumbWidth / imageWidth 
    : thumbHeight / imageHeight;

destWidth = imageWidth * zoomFactor;
destHeight = imageHeight * zoomFactor;

drawImage(
    (thumbWidth - destWidth) >> 1,
    (thumbHeight - destHeight) >> 1,
    destWidth,
    destHeight);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top