环境:
win7 python 2.7.13
安装:
pip install image
http://pythonware.com/products/pil/官网有exe安装包
导入:
import Image
看下包是在PIL里
所以:from PIL import Image
1、打开,缩放,保存
# 打开一个jpg图像文件,注意路径要改成你自己的: im = Image.open('static/test.png') # 获得图像尺寸: w, h = im.size print w,h # 缩放到50%: im.thumbnail((w*2, h*2)) # 把缩放后的图像用jpeg格式保存: im = im.convert('RGB')#解决IOError: cannot write mode RGBA as JPEG报错问题 im.save('static/th.jpeg', 'jpeg')
2、模糊图片
from PIL import Image,ImageFilter
im = Image.open('static/test.png')
im = im.convert('RGB')
im = im.filter(ImageFilter.BLUR)
im.save('static/filter.jpeg', 'jpeg')
3、生成图片
比如生成验证码图片
from PIL import Image, ImageDraw, ImageFont, ImageFilter import random # 随机字母: def rndChar(): return chr(random.randint(65, 90)) # 随机颜色1: def rndColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) # 随机颜色2: def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) # 240 x 60: width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255)) # 创建Font对象: font = ImageFont.truetype('C:WindowsFontsArial.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(image) # 填充每个像素: for x in range(width): for y in range(height): draw.point((x, y), fill=rndColor()) # 输出文字: for t in range(4): draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2()) # 模糊: image = image.filter(ImageFilter.BLUR) image.save('new.jpg', 'jpeg')
ps:font = ImageFont.truetype('C:WindowsFontsArial.ttf', 36),创建对象时,设置了字体的绝对路径。解决IOError: cannot open resource。
windows的字体目录路径:C:WindowsFonts
linux的字体目录路径:/Library/Fonts/
当能自动找到字体路径时可以简写为:font = ImageFont.truetype('Arial.ttf', 36)