Cropping image - Image.crop function not working

邮差的信 提交于 2021-01-27 07:16:37

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/7735554/cropping-image-image-crop-function-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!