Resize an Image

Problem

You want to resize ‘Patches with ball.jpg’ to 640x480.

Solution

import Draft

img = Draft.Image.ReadFromFile( 'Patches with ball.jpg' )
img.Resize( 640, 480 )
img.WriteToFile( 'Patches with ball 640x480.jpg' )

Discussion

In addition to the width and height, Resize has two optional parameters, type and border. Type specifies how the image should be scaled to fit the new size.The default value is 'fit', which scales the image as large as possible, keeping the aspect ratio locked, while staying inside the bounds of the new image size. If the aspect ratio of the new size does not match the aspect ratio of the old size, the unfilled portion of the resized image will be evenly distributed on both sides of the image, either top and bottom, or left and right. Most options for type preserve the aspect ratio of the original image. These aspect-ratio-preserving types include: 'none' (don’t scale the image at all), 'width' (scale the image to fit the new width), 'height' (scale the image to fit the new height), 'fit' (already described), and 'fill' (scale the image as small as possible while covering the new image size). One option does not preserve the aspect ratio: 'distort' (scale the image to match the new width and height, changing the aspect ratio as necessary).

We can use the type parameter to letterbox or pillarbox the original image inside the new dimensions. To letterbox a shorter image within an image with a taller aspect ratio, choose type='width':

img.Resize( 640, 480, type='width' )

To pillarbox a narrower image within an image with a wider aspect ratio, choose type='height':

img.Resize( 1280, 720, type='height' )

Except for 'distort' and 'fill', the type options could leave portions of the new image with no data. We specify how these areas are to be filled using the optional border parameter. There are two border options, 'transparent' (default), and 'stretch'. Choosing (or defaulting to) 'transparent' sets the border pixels to black with an alpha of zero, while ‘stretch’ copies the pixels at the edges of the original image, and uses those values to fill the border. For example, to resize the image to 1024x768 with no scaling, and a stretched border, use:

img.Resize( 1024, 768, type='none', border='stretch' )

See Also

For more information on the import statement, ReadFromFile(), and WriteToFile(), see the Creating an Image section of this Cookbook