美文网首页
Python 练习册 0000、0010题 (pillow库)

Python 练习册 0000、0010题 (pillow库)

作者: 海上牧云l | 来源:发表于2017-04-21 22:18 被阅读100次

最近找到一个练手的好东西,Python 练习册,每天一个小程序,花了几天时间搞完了,感觉不错,从中学习了很多库的使用。这里把答案和一些扩展的东西总结下。

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

头像头像

答案

img = Image.open('avatar.png')

draw = ImageDraw.Draw(img)
font = ImageFont.truetype("PalanquinDark-Regular.ttf", 70)
draw.text((img.size[0]-50, -20), "5", font=font, fill=(255, 0, 0))
img.save('avatar2.png')
img.show()

pillow其他使用

# 改变图片大小
# out = img.resize((128, 128))
# img.thumbnail(size)
# img.save('size.jpg')
# 复制粘贴
# box = (0, 0, 100, 100)
# region = img.crop(box)
# img.paste(region, (-100, -100, 0, 0))
# 镜像
# out = img.transpose(Image.FLIP_LEFT_RIGHT)
# 逆时针90度
# out = img.transpose(Image.ROTATE_90)
# out = img.rotate(90)
# img.show()
# 线
# draw.line([(0, img.size[1]/2), (img.size[0], img.size[1]/2), (0, 0)], fill=24)
# draw.line([(img.size[0]/2, img.size[1]), (img.size[0]/2, 0)], fill=24)
# del draw
# img.save('save.png')

第 0010 题:使用 Python 生成类似于下图中的字母验证码图片


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


def get_random_num():
    num_list = list()
    for i in range(4):
        num_list.append(random.choice(string.ascii_letters))
    return num_list


def get_random_color():
    color = (random.randint(30, 100), random.randint(30, 100), random.randint(30, 100))
    return color


def get_code_pic():
    image = Image.new('RGB', (240, 60), (180, 180, 180))
    font = ImageFont.truetype('font.ttf', 40)
    draw = ImageDraw.Draw(image)
    code = get_random_num()
    for i in range(4):
        draw.text((60*i+20, 0), code[i], font=font, fill=get_random_color())
    for _ in range(random.randint(1500, 3000)):
        draw.point((random.randint(0, 240), random.randint(0, 60)), fill=get_random_color())
    image = image.filter(ImageFilter.SMOOTH_MORE)
    # image.save('C:\\Users\\L\\Desktop\\img\\' + name + '.jpg')
    image.show()


get_code_pic()

相关文章

网友评论

      本文标题:Python 练习册 0000、0010题 (pillow库)

      本文链接:https://www.haomeiwen.com/subject/xpsjzttx.html