图片处理
pillow
基于PIL的图像处理标准库
pip3 install pillow
缩略图
from PIL import Image
# 打开图像文件
im = Image.open('1.png') # type: Image.Image
# 获取图像宽、高
w, h = im.size
# 缩放50%
im.thumbnail((w // 2, h // 2))
im.save('thumbnail.jpg', 'png')
验证码
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 随机字母
def rndChar():
return chr(random.randint(65, 90))
# 随机每个像素点的颜色
def rndPointColor():
return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)
# 随机字母颜色
def rndCharColor():
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('Arial.ttf', 36)
# 创建Draw对象
draw = ImageDraw.Draw(image)
# 在画布上的每个像素点画一个随机颜色
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndPointColor())
# 画随机的字母
for t in range(4):
draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndCharColor())
# 模糊
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
subprocess
使用 ImageMagick 拼接长图
from pathlib import Path, PurePath
from subprocess import run
p = Path(Path.cwd().joinpath("img"))
cmd = ['convert', '-append']
for i in p.iterdir():
if PurePath(i).suffix in ['.png', '.jpg']:
cmd.append(str(i))
cmd.append(p.joinpath("result.jpg"))
run(cmd)