python小测试答案第零周_python练习册第零题

说明

这个是网上一些大佬做的一套练习题,总共有25题,训练大家python在文件读取、文本处理、数据库、网页等方向的熟练度,十分有用。github地址在这:

上不了github的可以直接搜名字,应该能搜到。

我这个笔记集也是只记了五道题。。。我大概多做了一两题吧,唉。。。。。。

题目:

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

学习内容

虽然python学的不久,但是用Pillow库解决图像方面的问题还是知道的。这个题目的解决思路就是:如何用Pillow库实现在一个图像的某一个像素位置插入一个text字段。

Load an Image

To load an image from a file, use the open() function in the Image module:

>>> from PIL import Image

>>> im = Image.open("hopper.ppm")

If successful, this function returns an Image object. If the file cannot be opened, an IOError exception is raised.

ImageFont Module

The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the PIL.ImageDraw.Draw.text() method.

font字体在Image模块中被当做bitmap位图处理,也就是一种图片格式。添加字体其实就是在一张图片上添加bitmap格式的font图片。

from PIL import ImageFont, ImageDraw

draw = ImageDraw.Draw(image)

# use a bitmap font

font = ImageFont.load("arial.pil")

draw.text((10, 10), "hello", font=font)

# use a truetype font

font = ImageFont.truetype("arial.ttf", 15)

draw.text((10, 25), "world", font=font)

ImageDraw Module

Example: Draw Partial Opacity Text

from PIL import Image, ImageDraw, ImageFont

# get an image

base = Image.open('Pillow/Tests/images/hopper.png').convert('RGBA')

# make a blank image for the text, initialized to transparent text color

txt = Image.new('RGBA', base.size, (255,255,255,0))

# get a font

fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)

# get a drawing context

d = ImageDraw.Draw(txt)

# draw text, half opacity

d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))

# draw text, full opacity

d.text((10,60), "World", font=fnt, fill=(255,255,255,255))

out = Image.alpha_composite(base, txt)

out.show()

PIL.ImageDraw.ImageDraw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left", direction=None, features=None)

解决代码

from PIL import Image, ImageFont, ImageDraw

image = Image.open(r'C:\Users\ChanWunsam\Desktop\0.png')

draw = ImageDraw.Draw(image)

font = ImageFont.truetype('arial.ttf', 25)

draw.text((230,10), '10', fill='red', font=font)

# del draw ## 释放ImageDraw.Draw缓存,不过不影响结果,感觉也非必要

image.save(r'C:\Users\ChanWunsam\Desktop\0_1.png', format='PNG')

image.close()

别人的解决方法

我的方法是看文档做出来的,确实没有看过别人的源码。不过看起来思路一样,就是他的在细节方面比我更好。

from PIL import Image, ImageFont, ImageDraw

image = Image.open('0.png')

w, h = image.size

font = ImageFont.truetype('arial.ttf', 50)

draw = ImageDraw.Draw(image)

draw.text((4*w/5, h/5), '5', fill=(255, 10, 10), font=font)

image.save('0.0.png', 'png')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值