python PIL 图片处理库

OO~ posted @ 2015年1月12日 14:46 in python , 3187 阅读

    最近学习了 python 的图形处理库 PIL,深刻体会到 python 的强大。就图片的简单处理,如高亮、旋转、resize 等操作,特别是对图片的批量处理,python 较 photoshop 等图片处理工具要来的更容易、更方便。

    安装 PIL 库后,根据自己的需求阅读 PIL 库的使用手册。下面是我在使用该 lib 时,遇到的一些问题和感悟。

需求:在图片右上方添加如手机 App 上消息提醒的数字。

具体实现代码如下:

#!/usr/bin/python

import os, sys
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

def main():
	img = Image.open("thumb.png")
	fontsize = img.size[1] / 16
	x = img.size[0] - fontsize

	draw = ImageDraw.Draw(img)
	font = ImageFont.truetype("/usr/share/fonts/truetype/msttcorefonts/arial.ttf", fontsize)
	draw.text((x, 0), "9", font=font, fill="red")

	del draw
	img.save("result.png")
	img.show()

if __name__== '__main__':
	main()

分析:

1. 坐标 (0, 0) 表示左上角,整个图片类似镶嵌在坐标的第四像限;img.size 是一个二位数组,依次位图片的宽和高。

2. 在图片上添加内容时注意对应内容也会占位置,所以不能当作点即 pixel 来看待,实际处理时需要考虑添加对象的 size,这就对应代码中右上角坐标 x 的获取。

3. ImageFont 的获取有很多方法,其中较简单的方法从 truetype 中获取,对应 font 存放的位置一般是 /usr/share/fonts/...

Avatar_small
Assam Board Model Pa 说:
2022年9月07日 17:17

Assam Board Model Paper 2023 Class 6 Pdf Download with Answers for English Medium, Bangali Medium, Hindi Medium & Assamese Medium Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. Assam Board Model Paper Class 6 New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.

Avatar_small
Emma 说:
2023年1月12日 13:36

PIL is the Python Imaging Library which provides support for a wide range of image file formats. It is used for basic image processing tasks such as resizing, cropping, and converting home buying Great Barrington images to different formats. PIL can also be used for more advanced image processing tasks such as creating thumbnails, adding text to images, and composing multiple images into a single image.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter