有没有我忽略的明显的方法?我只是想做个缩略图。
当前回答
如果你不想/不需要用Pillow打开图像,使用这个:
from PIL import Image
new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))
其他回答
已经更新了上面的答案“tomvon”
from PIL import Image
img = Image.open(image_path)
width, height = img.size[:2]
if height > width:
baseheight = 64
hpercent = (baseheight/float(img.size[1]))
wsize = int((float(img.size[0])*float(hpercent)))
img = img.resize((wsize, baseheight), Image.ANTIALIAS)
img.save('resized.jpg')
else:
basewidth = 64
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('resized.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
######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)
举个丑陋的例子。
函数获取像pic[0-9a-z]这样的文件。[扩展]",将它们调整为120x120,移动部分到中心,并保存到"ico[0-9a-z]。[扩展]”,肖像和风景作品:
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:])
如果你不想/不需要用Pillow打开图像,使用这个:
from PIL import Image
new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))