开发者

Python PIL: How to save cropped image?

I have a script which creates an image and the it crops it. The problem i开发者_运维知识库s 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)


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.


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)


Here is a fully working aswer with a NEW version of PIL 1.1.7. The crop coordinates are now upper left corner and lower right corner (NOT the x, y, width, height).

The version number for python is: 2.7.15

and for PIL: 1.1.7

# -*- coding: utf-8 -*-

from PIL import Image
import PIL, sys

print sys.version, PIL.VERSION


for fn in ['im000001.png']:

    center_x    = 200
    center_y    = 500

    half_width       = 500
    half_height      = 100

    imageObject = Image.open(fn)

    #cropped = imageObject.crop((200, 100, 400, 300))


    cropped = imageObject.crop((center_x - half_width,
                                center_y - half_height, 
                                center_x + half_width,
                                center_y + half_height,
                                ))

    cropped.save('crop_' + fn, 'PNG')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜