我有一个脚本,它创建了一张图片并进行了裁剪。问题是,在调用crop()方法后它没有保存在磁盘上。
crop = image.crop(x_offset, Y_offset, width, height).load()
return crop.save(image_path, format)
我有一个脚本,它创建了一张图片并进行了裁剪。问题是,在调用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
。
box = (x_offset, y_offset, x_offset + width, y_offset + height)
。 - ofekpload()
返回的对象作为图像对象。根据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)
这里是一个完全可用的答案,使用了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')