PIL是什么:
PIL,全称Python Image Library,主要作用是图像处理,可用于图片剪切、粘贴、缩放、镜像、水印、颜色块、滤镜、图像格式转换、色场空间转换、验证码、旋转图像、图像增强、直方图处理、插值和滤波等功能
简单使用记录:
1.安装工具包
pip3 install Pillow
代码联系:
1.分离RGB图片的三个颜色通道实现颜色交换
from PIL import Image
from PIL import ImageFilter
from PIL import ImageDraw
from PIL import ImageFont
# 分离RGB图片的三个颜色通道实现颜色交换
def RGBImageTest():
image = Image.open("李成敏.webp")
r, g, b = image.split()
newg = g.point(lambda i: i * 0.8)
newb = g.point(lambda i: i < 100)
om = Image.merge(image.mode, (r, newg, newb))
om.save("20221213.jpeg")
om.show()
if __name__ == '__main__':
RGBImageTest()
原始图片:李成敏.webp
执行RGBImageTest()函数效果:
2.图像的过滤和增强
from PIL import Image
from PIL import ImageFilter
from PIL import ImageDraw
from PIL import ImageFont
# 图像的过滤和增强
def ImageFileterTest():
image = Image.open(r"李成敏.webp")
# 滤镜类型:
# BLUR 模糊滤镜
# CONTOUR 轮廓
# EDGE_ENHANCE 边界加强
# EDGE_ENHANCE_MORE 边界加强(阈值更大)
# EMBOSS 浮雕滤镜
# FIND_EDGES 边界滤镜
# SMOOTH 平滑滤镜
# SMOOTH_MORE 平滑滤镜(阈值更大)
# SHARPEN 锐化滤镜
# DETAIL 细节滤镜
openImage = image.filter(ImageFilter.FIND_EDGES)
openImage.save("20221213.jpg")
openImage.show()
if __name__ == '__main__':
ImageFileterTest()
执行效果:
3.自定义字体
from PIL import Image
from PIL import ImageFilter
from PIL import ImageDraw
from PIL import ImageFont
# 自定义字体
def ImageFontTest():
image = Image.new(mode='RGB', size=(600, 80), color=(255, 234, 222))
draw = ImageDraw.Draw(image, mode='RGB')
font = ImageFont.truetype('hanyixiaosongrongfan.ttf', 50)
draw.text([15, 5], "2022 辛苦了, 相信越来越好, 致自己", 'red', font=font)
with open('2022 加油.png', 'wb') as f:
image.save(f, format='png')
image.show()
if __name__ == '__main__':
ImageFontTest()
运行效果:
4.图片旋转
from PIL import Image
from PIL import ImageFilter
from PIL import ImageDraw
from PIL import ImageFont
#图片旋转
def TransposeTest():
image = Image.open("李成敏.webp")
# Image.transpose(method) method 参数列表
# Image.FLIP_LEFT_RIGHT:左右水平翻转;
# Image.FLIP_TOP_BOTTOM:上下垂直翻转;
# Image.ROTATE_90:图像旋转90度;
# Image.ROTATE_180:图像旋转180度;
# Image.ROTATE_270:图像旋转270度;
# Image.TRANSPOSE:图像转置;
# Image.TRANSVERSE:图像横向翻转
# 1.水平翻转
img1 = image.transpose(Image.FLIP_LEFT_RIGHT)
#2.垂直翻转
img2 = image.rotate(180)
#水平+垂直翻转
img3 = image.transpose(Image.FLIP_LEFT_RIGHT).rotate(180)
#调用画图模板
draw = ImageDraw.Draw(img1)
font = ImageFont.truetype('hanyixiaosongrongfan.ttf', 80)
draw.text([480, 60], "2022 辛苦了, 相信越来越好, 致自己\n\r\r\r\r 2022.12.13", 'red', font=font)
img1.show()
if __name__ == '__main__':
TransposeTest()
运行效果:
5.图片缩放
from PIL import Image
from PIL import ImageFilter
from PIL import ImageDraw
from PIL import ImageFont
#图片缩放
def ZoomImageTest():
image = Image.open("李成敏.webp")
w,h = image.size
image.thumbnail((w/10,h/10))
image.show()
if __name__ == '__main__':
ZoomImageTest()
运行效果:
-------------------------------------------------------------------------------------------------------------------------------
再见了,行程码(2022-12-13)!
------人这一生会遭遇到很多的告别,告别让我们成长,学会告别,我们会变得更加成熟-------