Crop an Image


You wish to crop an image, ‘Patches with ball.jpg’, coming in 100 pixels on the left, 80 on the bottom, 200 on the right, and 150 on the top.


import Draft

img = Draft.Image.ReadFromFile( 'Patches with ball.jpg' )
img.Crop( 100, 80, img.width - 200, img.height - 150 )
img.WriteToFile( 'Patches with ball (cropped).jpg' )


Here we’ve decided that we want to remove parts of the image to improve the composition of the remaining image. The parameters to Crop() specify the left edge, bottom edge, right edge, and top edge, each measured in pixels from either the left or bottom edges of the uncropped image. In this example, we’re removing 100 pixels from the left edge, 80 pixels from the bottom edge, 200 pixels from the right edge, and 150 pixels from the top edge.

Suppose you know how much you want to crop in inches (or cm), rather than how many pixels. You can convert this number from inches to pixels by using the image resolution. If we wanted to crop, say 0.75 inches off of each edge of an image whose resolution is 300 pixels per inch, then we can compute the number of pixels to crop by multiplying 0.75 inches by 300 ppi to get 225 pixels:

inches = 0.75
ppi = 300
cropAmt = inches * ppi

img.Crop( cropAmt, cropAmt, img.width - cropAmt, img.height - cropAmt )

See Also

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