如何拍摄图像并从中心裁剪出3x2比例的图像? [英] How can I take an image and get a 3x2 ratio image cropped from the center?
问题描述
有没有简单的方法可以做到这一点? 在Python中,我创建了一个脚本,用于从图像中获取方盒" ...基于中心.
Is there an easy way to do this? In Python, I created a script to get a "square box" from an image...based on the center.
但是,那杀死了我的一些脑细胞.是否有一种简单的方法可以根据中心为3x2(3宽度,2高度)执行此操作?
However, that killed some of my brain cells. Is there an easy way to do this for a 3x2 (3 width, 2 height), based on the center?
这是我的方框"脚本,但我不想为3x2修改它.
This is my "square box" script, but I don't feel like modifying it for the 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
在线上有可以满足我需要的脚本吗?
Is there a script online that can do what I need?
推荐答案
使用定义为imagex/imagey的宽高比,因此您将3/2用于3:2,将16/9用于16:9等./p>
Use an aspect ratio which is defined as imagex/imagey, so you use 3/2 for 3:2, 16/9 for 16:9 etc.
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
您可能希望在某个时候检查舍入错误,但否则会这样做.
You might want to check for roundoff errors at some point, but otherwise this does it.
这篇关于如何拍摄图像并从中心裁剪出3x2比例的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!