Python中Pillow图像处理库(PIL Fork)的应用

@spiritree  October 13, 2016

Docs:https://pillow.readthedocs.io/en/3.4.x/

本文所用到的:

  • Image模块

Image.open(路径) 打开图片
Image.new(mode, size, color=0) 创建一个新图片

  • ImageDraw模块

ImageDraw.Draw(im, mode=None) im为image的对象
ImageDraw.Draw.point(xy, fill=None) xy为坐标 fill是填充颜色
ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left") 填写文字

  • ImageFilter模块

im1 = im.filter(ImageFilter.BLUR) 模糊

  • ImageFont模块

ImageFont.truetype(font=None, size=10, index=0, encoding='') 设置字体

将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果

from PIL import Image, ImageFont, ImageDraw
def addNum(image):
    font = ImageFont.truetype('arial.ttf', 36)
    fillcolor = "#ff0000"   #红色
    draw = ImageDraw.Draw(image)
    draw.text((image.size[0]-20, 0), '1', font=font, fill=fillcolor)

if __name__ == '__main__':
    image = Image.open('/python/mypicture.jpg')
    addNum(image)
    image.show()

生成字母验证码图片
http://stackoverflow.com/questions/2823316/generate-a-random-letter-in-python

import string
import random
from PIL import Image, ImageFont, ImageDraw, ImageFilter

IMAGE_MODE = 'RGB'
IMAGE_FONT = 'arial.ttf'

def randomchar():
    return random.choice(string.ascii_letters)

def randomcolor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

def backgroundcolor():
    return (random.randint(32,127), random.randint(32,127), random.randint(32,127))

height = 60
width = height * 5
image = Image.new(IMAGE_MODE, (width, height), (255, 255, 255))
#   创建font对象
font = ImageFont.truetype(IMAGE_FONT, 36)
#   创建draw对象
draw = ImageDraw.Draw(image)
#   向图像填充颜色
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=backgroundcolor())
#   向图像填写字母
for i in range(4):
    draw.text((height * i + 10, 10), randomchar(), font=font, fill=randomcolor())
#   模糊效果
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')

添加新评论