用PIL实现图片的旋转,缩放,合成

我们需要知道合成位置的中心点坐标,用中心点坐标,不使用左顶点的坐标是由于缩放过程容易计算。

假设A是局部透明的图片,我们希望把B放在A的底部,仅从A的透明部分显示B的部分。

步骤就是,

1、先创建空白的图片C,大小和A目标图片一样大。

2、对B进行缩放到指定大小B0

3、新建空白图片D,宽和高相等,等于B0的对角线长度,目的是防止旋转后丢失部分图像

4、将B0放到D的中间并旋转指定角度得到E。

5、将E合成到C的指定位置

6、将A合成到C上

from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
import math def combine_image_with_transparency(templateImg, pos, input_img):
#新建一张和目标图片同样大小的空白图片,颜色根据实际需要,这里是白色,透明的
tmpImg = Image.open(input_img).convert('RGBA')
pos = [float(point) for point in pos]
center_x, center_y = pos[0], pos[1]
dx = dy = 0
tmpImg_size = tuple(int(x * pos[2]) for x in tmpImg.size)
tmpImg = tmpImg.resize(tmpImg_size)
x = center_x - tmpImg.size[0] / 2
y = center_y - tmpImg.size[1] / 2
w, h = tmpImg.size
r = int(math.ceil(math.sqrt(w * w + h * h)))
# 新建正方形
empty_img = Image.new('RGBA', (r, r),(255, 255, 255, 255))
dx = int((r - w) / 2.0)
dy = int((r - h) / 2.0)
empty_img.paste(tmpImg, (dx, dy))
tmpImg = empty_img.rotate(pos[3])
# 将旋转之后的透明部分填充为白色
fff = Image.new('RGBA', tmpImg.size, (255,) * 4)
tmpImg = Image.composite(tmpImg, fff, tmpImg)
target.paste(tmpImg, (int(x - dx), int((y - dy))), tmpImg)
target.paste(templateImg, (0,0), templateImg)
return target if __name__ == '__main__':
imageFile = Image.open('./1.png').convert("RGBA")
pos = '226,169,0.205,-49'.split(',')
imageFile = combine_image_with_transparency(imageFile, pos, './2.jpg')
imageFile = imageFile.convert("RGB")
imageFile.save('./out.png')

最新文章

  1. 微信小程序常见问题集合(长期更新)
  2. iOS - AppRealTest App 真机测试
  3. 学习笔记-Kuaihu(仿知乎日报)
  4. 网络编程(一)——InetAddress
  5. Java的四种引用
  6. Laxcus大数据管理系统2.0(8)- 第六章 网络通信
  7. JavaEE是什么?
  8. HTML5入门1---Canvas画布
  9. Instruments-查看收集到的数据
  10. WPF控件---Border应用
  11. ssh 如何通过外网访问内网多台服务器
  12. 如何打开Nib文件
  13. Android使用surface直接显示yuv数据(三)
  14. Spring Boot的properties配置文件读取
  15. Jenkins+ANT+Jmeter 接口测试的实践(转载)
  16. final link failed: Nonrepresentable section on output
  17. 我的书单(Book List)
  18. 解惑 ["1", "2", "3"].map(parseInt) 为何返回[1,NaN,NaN]
  19. Visual Studio 2015 与 .NET 4.6 RTM 正式发布
  20. 15.unbuntu下安装vmware-tools

热门文章

  1. Keywords Search HDU - 2222(ac自动机板题。。)
  2. secureCRT mac 下破解
  3. C++11新利器
  4. python基础----模块、包
  5. Redis基操
  6. maven使用ss代理
  7. Struts2-从值栈中获取数据-EL表达式从值栈获取
  8. 【题解】Berland.Taxi Codeforces 883L 模拟 线段树 堆
  9. 题解【bzoj2038 [2009国家集训队]小Z的袜子(hose)】
  10. 管理lnmp常用命令,lnmp重启,start|stop|reload|restart等命令