Python PIL:如何保存裁剪后的图像?

7

我有一个脚本,它创建了一张图片并进行了裁剪。问题是,在调用crop()方法后它没有保存在磁盘上。

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

3
发生了什么?是否出现异常?“image_path”和“format”是什么? - codeape
3个回答

13
你需要将参数作为元组传递给 .crop()。不要使用 .load()
box = (x_offset, Y_offset, width, height)
crop = image.crop(box)
return crop.save(image_path, format)

这就是你需要的全部内容。不过,我不确定为什么你正在返回保存操作的结果;它会返回None


根据文档,您需要 box = (x_offset, y_offset, x_offset + width, y_offset + height) - ofekp

1
主要问题是尝试使用由load()返回的对象作为图像对象。根据PIL文档:

在[PIL] 1.1.6及更高版本中,load返回一个像素访问对象,可用于读取和修改像素。访问对象的行为类似于二维数组[...]

试试这个:
crop = image.crop((x_offset, Y_offset, width, height))   # note the tuple
crop.load()    # OK but not needed!
return crop.save(image_path, format)

0

这里是一个完全可用的答案,使用了PIL 1.1.7的新版本。裁剪坐标现在是左上角右下角(而不是x、y、宽度、高度)。

Python的版本号为:2.7.15

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

在实际代码执行环境中,“for fn in ['im000001.png']:”的确切用法是什么? - Mike Chen
我用这个代码处理了多个文件,并且只测试了一个。for循环中的列表被替换为glob.glob(''*.PNG")。 - Juha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接