习题来源:
https://github.com/Yixiaohan/show-me-the-code
要学习Python的可以去试着刷下题。
我也是参考着别人的想法,再加上一些自己的思考和分析。希望经过自己的努力,能达到一个更高的水平。
分析
题目中涉及到对图片的处理,就需要用到Python中常用的第三方库Pillow。
对于Pillow的安装和使用,可以参考
http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320027235877860c87af5544f25a8deeb55141d60c5000。
#! usr/bin/env python
# 载入模块
from PIL imort Image, ImageDraw, ImageFont
image = Image.open('test.jpg') # 打开图像
draw = ImageDraw.Draw(image) # ImageDraw module creates drawing surface for image 创建绘画对象 #注(a)
addfont = ImageFont.truetype("arial.ttf", size=40)# 注(b)
width, height = image.size
draw.text((width-50, 0), '99', font=myfont, fill=(255, 0, 0)) #注(a)
image.show() # 显示
# image.save('result.jpg', 'jpeg') # 保存
注
Pillow官方文档
https://pillow.readthedocs.org/
(a)ImageDraw Module
The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.(该模块给图像提供了图形化处理,可以利用该模块创建一个新的图像,然后可以在新图像上进行注释修整等)
常见的Function:
class PIL.ImageDraw.Draw(im, mode=None)
功能:Creates an object that can be used to draw in the given image.
(该函数创建了一个对象,可以在给定图像上进行画图)
参数: im : 要处理的图片
mode ;图像颜色值的可选模式,如果省略,默认模式图像的模式。一般的是省略。
常用Method
(1)PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left")
功能: Draws the string at the given position(在给定位置画上String符号)
参数:xy – Top left corner of the text. (text的左上角)
If it contains anynewline characters, the text is passed
on to multiline_text(),如果包含换行符,则使用multiline_text()
text – Text to be drawn. 需要被画在图像上的文本
fill - 填充颜色
font -字体
spacing – If the text is passed on to multiline_text(), the
number of pixels between lines.
align – If the text is passed on to multiline_text(),
“left”, “center” or “right”
(2)PIL.ImageDraw.Draw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left")
与(1)类似
(b)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.
定义了相同名字的类,这个类的实例存储的是位图字体。常常和PIL.ImageDraw.Draw.text() method一起使用。
Functions:
(1)PIL.ImageFont.load(filename)
This function loads a font object from the given bitmap font file, and returns the corresponding font object.
载入字体。从给定的位图字体文件载入字体对象。
参数: filename – Name of font file.
(2)PIL.ImageFont.truetype(font=None, size=10, index=0, encoding='')
加载一个TrueType或OpenType字体文件,并创建一个字体对象.
参数:font- 字体文件。在win下会自动去Font目录下寻找
size- 字体大小
index- Which font face to load (default is first available face??(不理解)
encoding --字体编码。Unicode(默认)
本文介绍如何使用Python的Pillow库对图像进行处理,包括添加文本和设置字体样式。通过具体的代码示例,读者可以了解如何在图像上绘制文字,并掌握ImageDraw和ImageFont模块的基本用法。
3628

被折叠的 条评论
为什么被折叠?



