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.