48

I installed Python Pillow and am trying to crop an image.

Other effects work great (for example, thumbnail, blurring image, etc.)

Whenever I run the code below I get the error:

tile cannot extend outside image

test_image = test_media.file
original = Image.open(test_image)

width, height = original.size   # Get dimensions
left = width/2
top = height/2
right = width/2
bottom = height/2
cropped_example = original.crop((left, top, right, bottom))

cropped_example.show()

I used a cropping example I found for PIL, because I couldn't find one for Pillow (which I assumed would be the same).

bbrooke
  • 2,267
  • 10
  • 33
  • 41
  • 1
    possible duplicate of http://stackoverflow.com/questions/1076638/trouble-using-python-pil-library-to-crop-and-save-image – xor Dec 03 '13 at 21:17

2 Answers2

84

The problem is with logic, not Pillow. Pillow is nearly 100% PIL compatible. You created an image of 0 * 0 (left = right & top = bottom) size. No display can show that. My code is as follows

from PIL import Image

test_image = "Fedora_19_with_GNOME.jpg"
original = Image.open(test_image)
original.show()

width, height = original.size   # Get dimensions
left = width/4
top = height/4
right = 3 * width/4
bottom = 3 * height/4
cropped_example = original.crop((left, top, right, bottom))

cropped_example.show()

Most probably this is not what you want. But this should guide you towards a clear idea of what should be done.

rafee
  • 1,731
  • 18
  • 21
  • 22
    For anybody wondering what this does, it cuts out the outside edges of the image, leaving you with the center of the original image. The cropped image's dimensions end up being half of the original image's dimensions. Here's an example: if the image you're cropping is 100 x 100, `left` and `top` will both be set to `25` and `right` and `bottom` will both be set to `75`. Thus, you will end up with a 50 x 50 image, which will be the exact center of the original image. – Nick Aug 25 '14 at 22:16
10

pillow image crop code:

img2 = img.crop((200, 330, 730, 606)) # (left, top, right, bottom)

But, those who are in hurry or are stupid like me - here is an abstraction-:)

python pillow coordinate system abstraction

YoBro_29
  • 139
  • 1
  • 6