繁体   English   中英

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

[英]Python PIL: How to save cropped image?

我有一个脚本,可以创建一个图像并将其裁剪掉。 问题是,在我调用crop()方法后,它不会保存在磁盘上

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

您需要将参数传递给元组中的.crop() 并且不要使用.load()

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

这就是你所需要的。 虽然,我不确定你为什么要返回保存操作的结果; 它返回None

主要的麻烦是尝试使用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)

这是一个完全正常工作的aswer,带有新版本的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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM