Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL: How to save cropped image?

I have a script which creates an image and the it crops it. The problem is that after I call the crop() method it does not save on the disk

crop = image.crop(x_offset, Y_offset, width, height).load()
return crop.save(image_path, format)
like image 308
bogtan Avatar asked Jun 23 '11 15:06

bogtan


2 Answers

You need to pass the arguments to .crop() in a tuple. And don't use .load()

box = (x_offset, Y_offset, width, height)
crop = image.crop(box)
return crop.save(image_path, format)

That's all you need. Although, I'm not sure why you're returning the result of the save operation; it returns None.

like image 55
voithos Avatar answered Sep 28 '22 06:09

voithos


The main trouble is trying to use the object returned by load() as an image object. From the PIL documentation:

In [PIL] 1.1.6 and later, load returns a pixel access object that can be used to read and modify pixels. The access object behaves like a 2-dimensional array [...]

Try this:

crop = image.crop((x_offset, Y_offset, width, height))   # note the tuple
crop.load()    # OK but not needed!
return crop.save(image_path, format)
like image 44
antinome Avatar answered Sep 28 '22 07:09

antinome