jpg图片使用pil的resize后_如何使用PIL调整图像大小并保持其纵横比?
是否有一種顯而易見的方法可以解決這個問題? 我只是想制作縮略圖。
#1樓
PIL已經(jīng)可以選擇裁剪圖像
img = ImageOps.fit(img, size, Image.ANTIALIAS)
#2樓
我丑陋的例子。
函數(shù)獲取文件如:“pic [0-9a-z]。[extension]”,將它們調整為120x120,將部分移動到中心并保存到“ico [0-9a-z]。[extension]”,使用縱向和景觀:
def imageResize(filepath):
from PIL import Image
file_dir=os.path.split(filepath)
img = Image.open(filepath)
if img.size[0] > img.size[1]:
aspect = img.size[1]/120
new_size = (img.size[0]/aspect, 120)
else:
aspect = img.size[0]/120
new_size = (120, img.size[1]/aspect)
img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])
if img.size[0] > img.size[1]:
new_img = img.crop( (
(((img.size[0])-120)/2),
0,
120+(((img.size[0])-120)/2),
120
) )
else:
new_img = img.crop( (
0,
(((img.size[1])-120)/2),
120,
120+(((img.size[1])-120)/2)
) )
new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])
#3樓
定義最大尺寸。 然后,通過取min(maxwidth/width, maxheight/height)來計算調整大小比率。
適當?shù)某叽缡莖ldsize*ratio 。
當然還有一個庫方法來執(zhí)行此操作:方法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.ANTIALIAS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for '%s'" % infile
#4樓
總部設在@tomvon,我完成了以下工作:
調整寬度:
new_width = 680
new_height = new_width * height / width
調整高度:
new_height = 680
new_width = new_height * width / height
然后就是:
img = img.resize((new_width, new_height), Image.ANTIALIAS)
#5樓
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
總結
以上是生活随笔為你收集整理的jpg图片使用pil的resize后_如何使用PIL调整图像大小并保持其纵横比?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 股票条件单设置技巧?
- 下一篇: microsoftexchange邮箱容