有没有简单的方法来做到这一点? 在 Python 中,我创建了一个脚本来从图像中获取一个“方框”……基于中心。
但是,这杀死了我的一些脑细胞。对于基于中心的 3x2(3 宽,2 高),有没有一种简单的方法可以做到这一点?
这是我的“方框”脚本,但我不想为 3x2 修改它。
def letterbox(f,thumb_w=None,thumb_h=None):
try:
im = Image.open(StringIO(f))
imagex = int(im.size[0])
imagey = int(im.size[1])
thumb_size = (thumb_w,thumb_h) #what if it is too small!?? fix it.
if imagex > imagey:
setlen = imagey
left = (imagex - setlen)/2
top = 0
height = setlen
width = setlen
if imagey > imagex:
setlen = imagex
left = 0
top = (imagey - setlen)/2
heigth = setlen
width = setlen
if imagex == imagey:
left = 0
top = 0
height = imagey
width = imagex
box = (left,top,left+width,top+height)
im = im.crop(box)
#im.thumbnail(thumb_size,Image.ANTIALIAS)
new_file = StringIO()
im.save(new_file,'JPEG')
new_file.seek(0)
except Exception, e:
pass
return new_file
是否有在线脚本可以满足我的需求?
最佳答案
使用定义为 imagex/imagey 的宽高比,因此您使用 3/2 表示 3:2,使用 16/9 表示 16:9 等。
def letterbox(f,aspect_ratio=1):
try:
im = Image.open(StringIO(f))
imagex = int(im.size[0])
imagey = int(im.size[1])
width = min(imagex, imagey*aspect_ratio)
height = min(imagex/aspect_ratio, imagey)
left =(imagex - width)/2
top = (imagey - height)/2
box = (left,top,left+width,top+height)
im = im.crop(box)
new_file = StringIO()
im.save(new_file,'JPEG')
new_file.seek(0)
except Exception, e:
pass
return new_file
您可能想在某个时候检查舍入错误,否则就可以了。
关于python - 如何拍摄图像并获得从中心裁剪的 3x2 比例图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4094744/