有没有我忽略的明显的方法?我只是想做个缩略图。
当前回答
我试图为幻灯片视频调整一些图像的大小,因此,我想要的不仅仅是一个最大维度,而是一个最大宽度和最大高度(视频帧的大小)。 而且总有可能拍一个人像视频…… 图像。缩略图方法是有前途的,但我不能使它放大一个较小的图像。
所以当我在这里(或其他地方)找不到明显的方法时,我写了这个函数,并把它放在这里:
from PIL import Image
def get_resized_img(img_path, video_size):
img = Image.open(img_path)
width, height = video_size # these are the MAX dimensions
video_ratio = width / height
img_ratio = img.size[0] / img.size[1]
if video_ratio >= 1: # the video is wide
if img_ratio <= video_ratio: # image is not wide enough
width_new = int(height * img_ratio)
size_new = width_new, height
else: # image is wider than video
height_new = int(width / img_ratio)
size_new = width, height_new
else: # the video is tall
if img_ratio >= video_ratio: # image is not tall enough
height_new = int(width / img_ratio)
size_new = width, height_new
else: # image is taller than video
width_new = int(height * img_ratio)
size_new = width_new, height
return img.resize(size_new, resample=Image.LANCZOS)
其他回答
基于@tomvon,我完成了以下使用(选择你的案例):
a)调整高度(我知道新的宽度,所以我需要新的高度)
new_width = 680
new_height = new_width * height / width
b)调整宽度(我知道新的高度,所以我需要新的宽度)
new_height = 680
new_width = new_height * width / height
然后:
img = img.resize((new_width, new_height), Image.ANTIALIAS)
定义最大大小。 然后,通过取min(maxwidth/width, maxheight/height)来计算调整大小的比率。
合适的尺寸是旧尺寸*比例。
当然,还有一个库方法可以做到这一点:Image.thumbnail方法。 下面是来自PIL文档的一个(编辑过的)示例。
import os, sys
import Image
size = 128, 128
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.Resampling.LANCZOS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for '%s'" % infile
from PIL import Image
from resizeimage import resizeimage
def resize_file(in_file, out_file, size):
with open(in_file) as fd:
image = resizeimage.resize_thumbnail(Image.open(fd), size)
image.save(out_file)
image.close()
resize_file('foo.tif', 'foo_small.jpg', (256, 256))
我使用这个库:
pip install python-resize-image
如果你试图保持相同的纵横比,那么你不会调整原始大小的一些百分比吗?
例如,原来大小的一半
half = 0.5
out = im.resize( [int(half * s) for s in im.size] )
只是用更现代的包装器更新了这个问题 这个图书馆包枕头(PIL的一个叉子) https://pypi.org/project/python-resize-image/
允许你这样做:-
from PIL import Image
from resizeimage import resizeimage
fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()
在上面的链接中有更多的例子。