有没有我忽略的明显的方法?我只是想做个缩略图。
当前回答
定义最大大小。 然后,通过取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
其他回答
# Importing Image class from PIL module
from PIL import Image
# Opens a image in RGB mode
im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
# Size of the image in pixels (size of original image)
# (This is not mandatory)
width, height = im.size
# Setting the points for cropped image
left = 4
top = height / 5
right = 154
bottom = 3 * height / 5
# Cropped image of above dimension
# (It will not change original image)
im1 = im.crop((left, top, right, bottom))
newsize = (300, 300)
im1 = im1.resize(newsize)
# Shows the image in image viewer
im1.show()
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
下面的脚本创建所有JPEG图像的漂亮缩略图,保留128x128最大分辨率的纵横比。
from PIL import Image
img = Image.open("D:\\Pictures\\John.jpg")
img.thumbnail((680,680))
img.save("D:\\Pictures\\John_resize.jpg")
如果你试图保持相同的纵横比,那么你不会调整原始大小的一些百分比吗?
例如,原来大小的一半
half = 0.5
out = im.resize( [int(half * s) for s in im.size] )
对我来说最简单的方法
image = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)
例子
from PIL import Image, ImageGrab
image = ImageGrab.grab(bbox=(0,0,400,600)) #take screenshot
image = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)
image.save('Screen.png')