有没有我忽略的明显的方法?我只是想做个缩略图。
当前回答
这个脚本将使用PIL (Python成像库)将图像(somepic.jpg)调整为300像素的宽度和与新宽度成比例的高度。它通过确定300像素是原始宽度(img.size[0])的百分比,然后将原始高度(img.size[1])乘以该百分比来实现这一点。将“basewidth”更改为任何其他数字以更改图像的默认宽度。
from PIL import Image
basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
img.save('somepic.jpg')
其他回答
定义最大大小。 然后,通过取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
im = Image.open("image.png")
使用PIL Image。Resize (size, resample=0)方法,其中将图像的(宽度,高度)替换为2元组大小。
这将显示原始大小的图像:
display(im.resize((int(im.size[0]),int(im.size[1])), 0) )
这将显示图像大小的1/2:
display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )
这将显示你的图像的1/3大小:
display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )
这将显示你的图像的1/4大小:
display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )
等等
我试图为幻灯片视频调整一些图像的大小,因此,我想要的不仅仅是一个最大维度,而是一个最大宽度和最大高度(视频帧的大小)。 而且总有可能拍一个人像视频…… 图像。缩略图方法是有前途的,但我不能使它放大一个较小的图像。
所以当我在这里(或其他地方)找不到明显的方法时,我写了这个函数,并把它放在这里:
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)
from PIL import Image
img = Image.open('/your image path/image.jpg') # image extension *.png,*.jpg
new_width = 200
new_height = 300
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save('output image name.png') # format may what you want *.png, *jpg, *.gif
你可以合并PIL的Image。带有sys的缩略图。如果您的调整大小限制仅在一个维度(宽度或高度)上,请使用Maxsize。
例如,如果你想调整图像的大小,使其高度不超过100px,同时保持纵横比,你可以这样做:
import sys
from PIL import Image
image.thumbnail([sys.maxsize, 100], Image.ANTIALIAS)
记住这个形象。thumbnail将调整图像的大小,这与image不同。Resize,而不是返回调整后的图像,而不改变原始图像。
编辑:形象。ANTIALIAS会发出弃用警告,并将在PIL 10(2023年7月)中删除。相反,你应该使用重采样。兰索斯:
import sys
from PIL import Image
from PIL.Image import Resampling
image.thumbnail([sys.maxsize, 100], Resampling.LANCZOS)