您的位置:首页 > 编程语言 > Python开发

python接收图片变成缩略图

2016-11-02 18:42 232 查看

python图像处理库:Pillow初级教程

Image类

Pillow中最重要的类就是Image,该类存在于同名的模块中。可以通过以下几种方式实例化:从文件中读取图片,处理其他图片得到,或者直接创建一个图片。

使用Image模块中的open函数打开一张图片:

>>> from PIL import Image
>>> im = Image.open("lena.ppm")


如果打开成功,返回一个Image对象,可以通过对象属性检查文件内容

>>> from __future__ import print_function
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB


format属性定义了图像的格式,如果图像不是从文件打开的,那么该属性值为None;size属性是一个tuple,表示图像的宽和高(单位为像素);mode属性为表示图像的模式,常用的模式为:L为灰度图,RGB为真彩色,CMYK为pre-press图像。

如果文件不能打开,则抛出IOError异常。

当有一个Image对象时,可以用Image类的各个方法进行处理和操作图像,例如显示图片:

>>> im.show()


创建缩略图

infile = "static/update_img/img3.jpg"
outfile = os.path.splitext(infile)[0] + ".JPEG" #这句是去掉jpg
if infile != outfile:
try:
im = Image.open(infile)
print(im.size)
height_img = int(im.size[1]*750/im.size[0])
size = (750, height_img)
print(size)
im.thumbnail(size)
im.save(outfile)
except IOError:
print("cannot create thumbnail for", infile)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: