python3 pillow使用测试
# -*- encoding=utf-8 -*-
'''''
pil处理图片,验证,处理
大小,格式 过滤
压缩,截图,转换
图片库最好用Pillow
还有一个测试图片img.jpg, 一个log图片,一个字体文件
'''
# 图片的基本参数获取
try:
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
except ImportError:
import Image, ImageDraw, ImageFont, ImageEnhance
def compress_image(img, w=128, h=128):
'''''
缩略图
'''
img.thumbnail((w, h))
img.save('test1.png', 'PNG')
print(u'成功保存为png格式, 压缩为128*128格式图片')
def cut_image(img):
'''''
截图, 旋转,再粘贴
'''
# eft, upper, right, lower
# x y z w x,y 是起点, z,w是偏移值
width, height = img.size
box = (width - 200, height - 100, width, height)
region = img.crop(box)
# 旋转角度
region = region.transpose(Image.ROTATE_180)
img.paste(region, box)
img.save('test2.jpg', 'JPEG')
print(u'重新拼图成功')
def logo_watermark(img, logo_path):
'''''
添加一个图片水印,原理就是合并图层,用png比较好
'''
baseim = img
logoim = Image.open(logo_path)
bw, bh = baseim.size
lw, lh = logoim.size
baseim.paste(logoim, (bw - lw, bh - lh))
baseim.save('test3.jpg', 'JPEG')
print(u'logo水印组合成功')
def text_watermark(img, text, out_file="test4.jpg", angle=23, opacity=0.50):
'''''
添加一个文字水印,做成透明水印的模样,应该是png图层合并
http://www.pythoncentral.io/watermark-images-python-2x/
这里会产生著名的 ImportError("The _imagingft C module is not installed") 错误
Pillow通过安装来解决 pip install Pillow
'''
watermark = Image.new('RGBA', img.size, (255, 255, 255)) # 我这里有一层白色的膜,去掉(255,255,255) 这个参数就好了
FONT = "simhei.ttf"
size = 2
n_font = ImageFont.truetype(FONT, size) # 得到字体
n_width, n_height = n_font.getsize(text)
text_box = min(watermark.size[0], watermark.size[1])
while (n_width + n_height < text_box):
size += 2
n_font = ImageFont.truetype(FONT, size=size)
n_width, n_height = n_font.getsize(text) # 文字逐渐放大,但是要小于图片的宽高最小值
text_width = (watermark.size[0] - n_width) / 2
text_height = (watermark.size[1] - n_height) / 2
# watermark = watermark.resize((text_width,text_height), Image.ANTIALIAS)
draw = ImageDraw.Draw(watermark, 'RGBA') # 在水印层加画笔
draw.text((text_width, text_height),
text, font=n_font, fill="#21ACDA")
watermark = watermark.rotate(angle, Image.BICUBIC)
alpha = watermark.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
watermark.putalpha(alpha)
Image.composite(watermark, img, watermark).save(out_file, 'JPEG')
print(u"文字水印成功")
# 等比例压缩图片
def resizeImg(img, dst_w=0, dst_h=0, qua=85):
'''''
只给了宽或者高,或者两个都给了,然后取比例合适的
如果图片比给要压缩的尺寸都要小,就不压缩了
'''
ori_w, ori_h = im.size
widthRatio = heightRatio = None
ratio = 1
if (ori_w and ori_w > dst_w) or (ori_h and ori_h > dst_h):
if dst_w and ori_w > dst_w:
widthRatio = float(dst_w) / ori_w # 正确获取小数的方式
if dst_h and ori_h > dst_h:
heightRatio = float(dst_h) / ori_h
if widthRatio and heightRatio:
if widthRatio < heightRatio:
ratio = widthRatio
else:
ratio = heightRatio
if widthRatio and not heightRatio:
ratio = widthRatio
if heightRatio and not widthRatio:
ratio = heightRatio
newWidth = int(ori_w * ratio)
newHeight = int(ori_h * ratio)
else:
newWidth = ori_w
newHeight = ori_h
im.resize((newWidth, newHeight), Image.ANTIALIAS).save("test5.jpg", "JPEG", quality=qua)
print(u'等比压缩完成')
'''''
Image.ANTIALIAS还有如下值:
NEAREST: use nearest neighbour
BILINEAR: linear interpolation in a 2x2 environment
BICUBIC:cubic spline interpolation in a 4x4 environment
ANTIALIAS:best down-sizing filter
'''
# 裁剪压缩图片
def clipResizeImg(im, dst_w, dst_h, qua=95):
'''''
先按照一个比例对图片剪裁,然后在压缩到指定尺寸
一个图片 16:5 ,压缩为 2:1 并且宽为200,就要先把图片裁剪成 10:5,然后在等比压缩
'''
ori_w, ori_h = im.size
dst_scale = float(dst_w) / dst_h # 目标高宽比
ori_scale = float(ori_w) / ori_h # 原高宽比
if ori_scale <= dst_scale:
# 过高
width = ori_w
height = int(width / dst_scale)
x = 0
y = (ori_h - height) / 2
else:
# 过宽
height = ori_h
width = int(height * dst_scale)
x = (ori_w - width) / 2
y = 0
# 裁剪
box = (x, y, width + x, height + y)
# 这里的参数可以这么认为:从某图的(x,y)坐标开始截,截到(width+x,height+y)坐标
# 所包围的图像,crop方法与php中的imagecopy方法大为不一样
newIm = im.crop(box)
im = None
# 压缩
ratio = float(dst_w) / width
newWidth = int(width * ratio)
newHeight = int(height * ratio)
newIm.resize((newWidth, newHeight), Image.ANTIALIAS).save("test6.jpg", "JPEG", quality=95)
print('''
"old size %s %s" % (ori_w, ori_h)
print
"new size %s %s" % (newWidth, newHeight)
print
u"剪裁后等比压缩完成"
''')
if __name__ == "__main__":
'''''
主要是实现功能, 代码没怎么整理
'''
im = Image.open('img.jpg') # image 对象
compress_image(im)
im = Image.open('img.jpg') # image 对象
cut_image(im)
im = Image.open('img.jpg') # image 对象
logo_watermark(im, 'logo.png')
im = Image.open('img.jpg') # image 对象
text_watermark(im, 'arthas')
im = Image.open('img.jpg') # image 对象
resizeImg(im, dst_w=100, qua=85)
im = Image.open('img.jpg') # image 对象
clipResizeImg(im, 100, 200)
python3 pillow使用测试的更多相关文章
- Python中生成器和迭代器的区别(代码在Python3.5下测试):
https://blog.csdn.net/u014745194/article/details/70176117 Python中生成器和迭代器的区别(代码在Python3.5下测试):Num01–& ...
- 基于python3在nose测试框架的基础上添加测试数据驱动工具
[本文出自天外归云的博客园] Python3下一些nose插件经过2to3的转换后失效了 Python的nose测试框架是通过python2编写的,通过pip3install的方式安装的nose和相关 ...
- Python3基础 hasattr 测试类是否有指定的类属性
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- Windows下安装python2和python3双版本
现在大家常用的桌面操作系统有:Windows.Mac OS.ubuntu,其中Mac OS 和 ubuntu上都会自带python.这里我们只介绍下Windows(我用的Win10)环境下的pytho ...
- Python3学习笔记 - 准备环境
前言 最近乘着项目不忙想赶一波时髦学习一下Python3.由于正好学习了Docker,并深深迷上了Docker,所以必须趁热打铁的用它来创建我们的Python3的开发测试环境.Python3的中文教程 ...
- python3中,os.path模块下常用的用法总结
abspath basename dirname exists getatime getctime getmtime getsize isabs isdir isfile islink ismount ...
- 【转】Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1
转自:https://blog.csdn.net/AckClinkz/article/details/78538462 环境 >>> import sys >>> ...
- Python3学习笔记29-发送邮件
email模块用来构造邮件,smtplib模块用来发送邮件. 以QQ邮箱为例 想要在代码中使用QQ邮箱发送邮件,需要先在QQ邮箱-设置-账户中,开启SMTP服务,然后生成授权码.在进行验证账号时,用生 ...
- linux centos7安装python3
折腾 Python官网: https://www.python.org/ 查看相关评论,众人大呼python2与python3为两种语言,既然继承性不大,那我也就直接学python3了. 在系统选择, ...
随机推荐
- httpModules 与 httpHandlers
ASP.NET对请求处理的过程:当请求一个*.aspx文件的时候,这个请求会被inetinfo.exe进程截获,它判断文件的后缀(aspx)之后,将这个请求转交给ASPNET_ISAPI.dll,AS ...
- 3、Linux内核模块学习
一.内核模块的学习 内核的整体框架是非常的大,包含的组件也是非常多,如何将需要的组件包含在内核中呢?选择一,就是将所有的组件全部编译进内核,虽然需要的组件都可以使用,但是内核过分庞大,势必带来效率 ...
- CALayer的contentsRect
contentsRect 想像下contentsRect作为层内容的可视区域.内容的矩形区域(x,y,width,height)也是绑定到层的框架上的.contentRect是一个比例值,而不是屏幕上 ...
- C#CRC16 Modbus 效验算法
CRC校验(循环冗余校验)小知识 CRC即循环冗余校验码(Cyclic Redundancy Check):是数据通信领域中最常用的一种查错校验码,其特征是信息字段和校验字段的长度可以任意选定.循环冗 ...
- IOS与安卓的远程调试
本地调试H5页面方案总结 http://www.jianshu.com/p/a43417b28280 Fiddler 手机抓包 http://blog.csdn.net/gld824125233/ar ...
- [Hibernate开发之路](4)ID生成策略
一 对象关系数据库映射之Id 被映射的类必须定义相应数据库表主键字段.大多数类有一个JavaBeans风格的属性, 为每个实例包括唯一的标识. <id> 元素定义了该属性到数据库表主键字段 ...
- shell常用操作积累
1. 拼接字符串* #!/bin/sh write_log(){ local up_name=$ local num=${#string} ]; do up_name="$up_name*& ...
- 查看tcp各个连接状态的数量
4. 查看tcp各个连接状态的数量 下面对的 netstat -tan|awk '$1~/tcp/{aa[$NF]++}END{for (h in aa)print h,aa[h]}' SYN_SEN ...
- 8168开发之---1g内存换成512M的内存映射配置
最近在帮新来同事调式内存分配,起初是将config.bld 中的内存在标配的基础上减少sr1,和tiler 将dsp从9m增加到16m,然后编译通过, 可是在加载的时候卡住了,init.sh 过,lo ...
- Photoshop经常使用快捷键(2)
51.自由变换外框右键属性:ESC 取消 斜切:能够依照该调节边角点所引导出的两条边的角度进行移动.ctrl+shift 扭曲:随意点的调节. ctrl 透视:模拟近大远小的关系.ctrl+shif ...