Elisa
Elisa

Reputation: 7103

Cropping image - Image.crop function not working

I have following line of code for image cropping

im = Image.open('path/to/image.jpg')

outfile = "path/to/dest_img.jpg"
im.copy()

im.crop((0, 0, 500, 500))
im.thumbnail(size, Image.ANTIALIAS)
im.save(outfile, "JPEG")

But it doesn't seems cropping image. I have bigger image size e.g. 2048 x 1536 px.

[edited]

Here's solution too, I could not answer this question myself so adding answer here.

Actually crop return image with new handler, I realized where I make mistake. I should have assign crop in new handler, as bellow

crop_img = im.crop((0, 0, 500, 500))

Complete code below:

im = Image.open('path/to/image.jpg')

outfile = "path/to/dest_img.jpg"
im.copy()

crop_img = im.crop((0, 0, 500, 500))
crop_img.thumbnail(size, Image.ANTIALIAS)
crop_img.save(outfile, "JPEG")

Notice, after crop line, there is crop_img handler being used.

Upvotes: 4

Views: 10206

Answers (2)

retromuz
retromuz

Reputation: 799

You have forgotten to assign the return values in some statements.

im = Image.open('path/to/image.jpg')

outfile = "path/to/dest_img.jpg"

im = im.crop((0, 0, 500, 500))
im = im.thumbnail(size, Image.ANTIALIAS)
im.save(outfile, "JPEG")

Upvotes: 6

lc2817
lc2817

Reputation: 3742

You certainly want to do this:

from PIL import Image
im = Image.open('sth.jpg')

outfile = "sth2.jpg"
region=im.crop((0, 0, 500, 500))
#Do some operations here if you want but on region not on im!
region.save(outfile, "JPEG")

Upvotes: 2

Related Questions