Python给图片加文字和二维码等图片 您所在的位置:网站首页 python在图片中添加文字 Python给图片加文字和二维码等图片

Python给图片加文字和二维码等图片

2023-12-27 08:57| 来源: 网络整理| 查看: 265

给图片加文字,网上有很多,下面我不想在图片里面加文字,而是把文字加在图片上面当做标题,这样的做法可以不破坏原来的图片,另外还加了一个方法,除了加文字,还可以随意拼接图片,需要使用到pillow库

安装pillow:pip install pillow 卸载pillow:pip uninstall pillow 豆瓣的下载比较快:pip install -i https://pypi.douban.com/simple pillo

from PIL import Image from PIL import ImageFilter from PIL import ImageEnhance from PIL import ImageDraw,ImageFont #图片宽高尺寸 def getImgSize(fname): imgObj=Image.open(fname) return imgObj.size #获取图片宽度 def getImgWidth(fname): imgObj=Image.open(fname) return imgObj.size[0] #获取图片高度 def getImgHeight(fname): imgObj=Image.open(fname) return imgObj.size[1] ''' 给图片加文字 生成一张blankimg空白图片,加上文字之后为fontimg图片,宽度为oldimg原始图片的宽度 ''' def imgAddFont(blankimg,oldimg,fontimg): Image.new("RGB" ,(getImgWidth(oldimg),70),(255,255,255)).save(blankimg,"PNG"); im = Image.open(blankimg) draw = ImageDraw.Draw(im) fnt = ImageFont.truetype(r'C:\Windows\Fonts\simsun.ttc',22) draw.text((50, 20), '新鲜的水果,0元包邮出售!\n仅限三天,赶快订购,领取购物券进行购买即可!!!', fill='red', font=fnt) im.show() im.save(fontimg) imgAddFont('imgs/blank.png','imgs/1.jpg','newImgs/font.jpg') ''' 拼接图片,把上面生成的文字图片拼接到原图上面 生成一张宽度一致,高度为两张图片之和的空白长图 分别打开图片进行粘贴到空白长图里面 ''' def joinImg(fontimg,oldimg,newimg): w=getImgWidth(fontimg) fh=getImgHeight(fontimg) oh=getImgHeight(oldimg) blankLongImg=Image.new('RGBA',(w,fh+oh))#空白长图 fontimg1=Image.open(fontimg).resize((w, fh),Image.ANTIALIAS) blankLongImg.paste(fontimg1,(0,0)) oldimg1=Image.open(oldimg).resize((w, oh),Image.ANTIALIAS) blankLongImg.paste(oldimg1,(0,fh)) blankLongImg.save(newimg) print('新拼接的图片:'+newimg) joinImg('newImgs/font.jpg','imgs/1.jpg','newImgs/new.png') ''' 拼接上下两张图片 ''' def joinTwoImg(fontimg,topimg,bottomimg,newimg): w=getImgWidth(fontimg) fh=getImgHeight(fontimg) th=getImgHeight(topimg) bh=getImgHeight(bottomimg) blankLongImg=Image.new('RGBA',(w,fh+th+bh))#空白长图 fontimg1=Image.open(fontimg).resize((w, fh),Image.ANTIALIAS) blankLongImg.paste(fontimg1,(0,0)) topimg1=Image.open(topimg).resize((w, th),Image.ANTIALIAS) blankLongImg.paste(topimg1,(0,fh)) bottomimg1=Image.open(bottomimg).resize((w, bh),Image.ANTIALIAS) blankLongImg.paste(bottomimg1,(0,fh+th)) blankLongImg.save(newimg) print('新拼接的图片:'+newimg) joinTwoImg('newImgs/font.jpg','imgs/1.jpg','imgs/2.jpg','newImgs/new.png')



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有