AWS Thinkbox Discussion Forums

Resize with Letterbox or Pillarbox

Problem

You need to resize an image, while creating a letterbox or pillarbox to preserve the original aspect ratio.

Solution

Paste this into your script, after the first few lines that begin with “import” and “from”:

[code]def ResizeWithLetterbox(self, width, height):
if width <= 0:
raise RuntimeError(‘width must be a positive number’)
if height <= 0:
raise RuntimeError(‘height must be a positive number’)
sourceAR = float(self.width) / self.height
destAR = float(width) / height
if sourceAR == destAR:
self.Resize(width, height)
else:
image = copy.deepcopy(self)
self.Resize(width,height)
self.SetToColor(ColorRGBA(0, 0, 0, 1.0))
if sourceAR > destAR:
image.Resize(width,int(round(width/sourceAR)))
else:
image.Resize(int(round(height*sourceAR)),height)
self.CompositeWithPositionAndGravity(image, 0.5, 0.5, PositionalGravity.CenterGravity, CompositeOperator.CopyCompositeOp)

Image.ResizeWithLetterbox = ResizeWithLetterbox[/code]

Now you can call .ResizeWithLetterbox in your script instead of .Resize.

This recipe is deprecated. The Resize() function now creates a letterbox or pillarbox automatically. img.Resize( 1920, 1080 )

The old behavior is now called ‘distort’. To use the old ‘distort’ resize type: img.Resize( 1920, 1080, 'distort' )

Privacy | Site terms | Cookie preferences