【Python真的很强大】使用PIL合成图片

    目前有如下需求,想用python生成一些图文并茂的图片,然后再与另外一个图片合并(合并风格:局顶,局底,局左,局右),具体就是合并一个饼型图和其注释内容(每份扇型图的名字,所占百分比等). 

 

  原始图如下: source

 

代码部分:

 

from PIL import Image, ImageDraw, ImageFont, ImageFilter



def perform(wordPosition="bottom"):
     Img = Image.new("RGBA", pending_img_size,(255,255,255))
     Draw = ImageDraw.ImageDraw(Img, "RGBA")
     font_type="/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf"
     font_size = 16
     line_words_image_space = 10
     line_space = 5
     font = ImageFont.truetype(font_type, font_size)
     Draw.setfont(font)
     allPendingElements=[{'word':u"binding (GO:0005488)", 'color':"#666666"}, 
                         {'word':u"catalytic activity (GO:0003824)", 'color':"#cc99cc"}, 
                         {'word':u"enzyme regulator activity (GO:0030234)",'color':"#33ccff"} ,
                         {'word':u"receptor activity (GO:0004872)",'color':"#009900"},
                         {'word':u"transporter activity (GO:0005215)",'color':"#99ff99"}]
     if wordPosition == 'top':
          startPoint = (0,0)
          drawPos_y = startPoint[1]
          for  element  in allPendingElements:
               Draw.rectangle((0, drawPos_y, font_size, font_size  + drawPos_y), fill = element['color'])
               Draw.text((font_size + line_words_image_space , drawPos_y ), element['word'], fill='black')
               drawPos_y  += (line_space + font_size)
               
          baseim = Image.open( "/tmp/chartProducer.jsp.png" )
          baseim.resize((pending_img_size[0], pending_img_size[1]), Image.ANTIALIAS)
          Img.paste(baseim, (0, drawPos_y) )
          Img.save('/tmp/test.png','PNG')
     elif wordPosition == 'bottom':
          startPoint = (0,pending_img_size[0] + (line_space + font_size))
          drawPos_y = startPoint[1]
          for  element  in allPendingElements:
               Draw.rectangle((0, drawPos_y, font_size, font_size  + drawPos_y), fill = element['color'])
               Draw.text((font_size + line_words_image_space , drawPos_y ), element['word'], fill='black')
               drawPos_y  += (line_space + font_size)
               
          baseim = Image.open( "/tmp/chartProducer.jsp.png" )
          baseim.resize((pending_img_size[0], pending_img_size[1]), Image.ANTIALIAS)
          Img.paste(baseim, (0, 0) )
          Img.save('/tmp/test.png','PNG')          
     return Img

if __name__ == "__main__":
     pending_img_size=(400,600)
     perform("bottom").show()

 

合成后的图片:

result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值