如何使用PIL调整图像大小并保持其纵横比?
-
07-07-2019 - |
题
有一种明显的方法可以做到这一点,我错过了吗?我只是想制作缩略图。
解决方案
定义最大尺寸。
然后,通过 min(maxwidth / width,maxheight / height)
计算调整大小比率。
正确的大小是 oldsize * ratio
。
当然还有一种库方法:方法 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
其他提示
此脚本将使用PIL(Python成像库)调整图像(somepic.jpg)的大小,宽度为300像素,高度与新宽度成比例。它通过确定300像素的原始宽度(img.size [0])然后将原始高度(img.size [1])乘以该百分比来实现。改变“基带宽度”任何其他数字,以更改图像的默认宽度。
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.ANTIALIAS)
img.save('sompic.jpg')
我还建议使用PIL的缩略图方法,因为它会消除你的所有比例麻烦。
但有一个重要提示:替换
im.thumbnail(size)
与
im.thumbnail(size,Image.ANTIALIAS)
默认情况下,PIL使用Image.NEAREST过滤器进行大小调整,从而获得良好的性能,但质量很差。
基于@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)
PIL已经可以选择裁剪图像
img = ImageOps.fit(img, size, Image.ANTIALIAS)
from PIL import Image
img = Image.open('/your iamge 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 u want ,*.png,*jpg,*.gif
如果您尝试保持相同的宽高比,那么您不会调整原始尺寸的某个百分比吗?
例如,原始尺寸的一半
half = 0.5
out = im.resize( [int(half * s) for s in im.size] )
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
我丑陋的例子。
函数获取文件如:" 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:])
保持约束比率并传递最大宽度/高度的简单方法。不是最漂亮,但完成工作并且易于理解:
def resize(img_path, max_px_size, output_folder):
with Image.open(img_path) as img:
width_0, height_0 = img.size
out_f_name = os.path.split(img_path)[-1]
out_f_path = os.path.join(output_folder, out_f_name)
if max((width_0, height_0)) <= max_px_size:
print('writing {} to disk (no change from original)'.format(out_f_path))
img.save(out_f_path)
return
if width_0 > height_0:
wpercent = max_px_size / float(width_0)
hsize = int(float(height_0) * float(wpercent))
img = img.resize((max_px_size, hsize), Image.ANTIALIAS)
print('writing {} to disk'.format(out_f_path))
img.save(out_f_path)
return
if width_0 < height_0:
hpercent = max_px_size / float(height_0)
wsize = int(float(width_0) * float(hpercent))
img = img.resize((max_px_size, wsize), Image.ANTIALIAS)
print('writing {} to disk'.format(out_f_path))
img.save(out_f_path)
return
这是使用此功能运行批量图像大小调整的 python脚本。
我正在尝试为幻灯片视频调整一些图片的大小,因此,我想要的不是一个最大尺寸,而是最大宽度和最大高度(视频帧的大小) 。结果
并且总是存在肖像视频的可能性......
Image.thumbnail
方法很有前景,但我无法将其升级为较小的图像。
所以在我在这里(或者在其他地方)找不到明显的方法之后,我写了这个函数并把它放在这里以供将来使用:
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
new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))
我以这种方式调整了图像的大小并且它的工作非常好
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import os, sys
from PIL import Image
def imageResize(image):
outputIoStream = BytesIO()
imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS)
imageTemproaryResized.save(outputIoStream , format='PNG', quality='10')
outputIoStream.seek(0)
uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
## For upload local folder
fs = FileSystemStorage()
filename = fs.save(uploadedImage.name, uploadedImage)
只需使用更现代的包装器更新此问题 这个库封装了Pillow(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()
在上面的链接中添加了更多示例。