有没有我忽略的明显的方法?我只是想做个缩略图。
当前回答
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
其他回答
定义最大大小。 然后,通过取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
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
######get resize coordinate after resize the image using this function#####
def scale_img_pixel(points,original_dim,resize_dim):
multi_list = [points]
new_point_list = []
multi_list_point = []
for point in multi_list:
multi_list_point.append([point[0],point[1]])
multi_list_point.append([point[2],point[3]])
for lsingle_point in multi_list_point:
x1 = int((lsingle_point[0] * (resize_dim[0] / original_dim[0])))
y1 = int((lsingle_point[1] * (resize_dim[1] / original_dim[1])))
new_point_list.append(x1)
new_point_list.append(y1)
return new_point_list
points = [774,265,909,409]
original_dim = (1237,1036)
resize_dim = (640,480)
result = scale_img_pixel(points,original_dim,resize_dim)
print("result: ", result)
下面的脚本创建所有JPEG图像的漂亮缩略图,保留128x128最大分辨率的纵横比。
from PIL import Image
img = Image.open("D:\\Pictures\\John.jpg")
img.thumbnail((680,680))
img.save("D:\\Pictures\\John_resize.jpg")
你可以合并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)