Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cropping an image with Python Pillow

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).

like image 449
bbrooke Avatar asked Dec 03 '13 20:12

bbrooke


People also ask

How do you crop a picture in a Pillow Python?

The crop() function of the image class in Pillow requires the portion to be cropped as rectangle. The rectangle portion to be cropped from an image is specified as a four-element tuple and returns the rectangle portion of the image that has been cropped as an image Object.

How do I crop an image to a specific size in Python?

Use resize() to resize the whole image instead of cutting out a part of the image, and use putalpha() to create a transparent image by cutting out a shape other than a rectangle (such as a circle). Use slicing to crop the image represented by the NumPy array ndarray . Import Image from PIL and open the target image.


1 Answers

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.

like image 178
rafee Avatar answered Sep 22 '22 17:09

rafee