咨询电话:
15628812133
04
2023/02

python根据文字自动生成图像

发布时间:2023-02-04 14:39:28
发布者:神棍子
浏览量:
0

本次主要用到PIL库,该库中包含了图像旋转、改变大小格式转化、图像增强等许多图像处理功能。

安装方法:

pip install pillow

(如遇安装不成功,需要先升级pip 在重试操作)

  安装成功后可在命令行尝试输入form PIL import Image 查看是否成功

 

首先需要引入相关包:

from PIL import ImageFont

from PIL import Image

from PIL import ImageDraw

import os

import random

import time

import sys

设置路径变量

imgFontpath = r"F:\\project\\python" #主路径

imgFontpath += "\\imgFont\\"

#图片资源、文字资源的路径

python

fontPath = imgFontpath+'font\\' #文字路径

软件开发

imagePath = imgFontpath+'image\\' #背景图片路径

软件建设

#生成图片目录

cacheImagePath = imgFontpath +'cache\\'

取出资源路径中的所有资源文件名且随机选中一个文字和一张背景图片

fontListArr = os.listdir(fontPath)

imageListArr = os.listdir(imagePath)

#取出文件夹中所有文件名

fontRandomIndex = random.randint(0,len(fontListArr)-1)

imageRandomIndex = random.randint(0,len(imageListArr)-1)

#生成随机数

imageFilePath = imageListArr[imageRandomIndex]

fontFilePath = fontListArr[fontRandomIndex]

#取随机资源

 

打开图片资源

imgOpenObj = Image.open(imagePath+imageFilePath)

根据画布大小设置字体

fontSize = random.randint(int(imgOpenObj.height/10),int(imgOpenObj.width/10/2))  #字体大小 

fontOpenObj = ImageFont.truetype(fontPath+fontFilePath, fontSize)    

fontPosition = (fontSize,random.randint(0,20))

fontColor = (255,255,255)#字体颜色

填写要生成的文字

textContent = 平台商城系统模式软件技术开发服务商

 

考虑到图片换行问题将文字自动换行

LineFontLength = int((imgOpenObj.width - fontPosition[0]) / fontSize)

#一行有几个字

TotalLineLength = int(len(textContent) / LineFontLength)+1 #总行数

#循环插入换行符

def StringInsertStrIndex(oldText,InsertIndex,InsertStr):

    t1 = list(oldText)

    t1.insert(InsertIndex,InsertStr) # 1的位置插入'e'

    s1_new = ''.join(t1)  # 连接起来

    return s1_new

 

for i in range(TotalLineLength):

    textContent = StringInsertStrIndex(textContent,(LineFontLength*i),'\n')

打开画布设置资源

drawImage = ImageDraw.Draw(imgOpenObj)

drawImage.text(fontPosition, textContent, fontColor, font=fontOpenObj)

填写生成文件名称

imgFileName=平台商城系统模式软件技术开发服务商

保存图片

imgFileName += '.jpg'

imgFilePath = r''+cacheImagePath+""+imgFileName;

 # imgOpenObj.show() #预览图片

imgOpenObj.save(imgFilePath)

完整代码如下

python根据文字自动生成图像


关键词:
返回列表