随机生成汉字图片

11111111

1111111111111111111111111111

# -*- coding: utf-8 -*-
#python随机生成汉字图片的代码
#需要下载 Arial Unicode MS.ttf   到脚本目录
#需要 __init__.py 做文件路径定位

from PIL import Image,ImageDraw,ImageFont
import random
import math, string
import logging
import sys,os
import codecs
import datetime


class RandomChar():
    @staticmethod
    def Unicode():
        val = random.randint(0x4E00, 0x9FBF)
        return unichr(val)    

    @staticmethod
    def GB2312():
        head = random.randint(0xB0, 0xCF)
        body = random.randint(0xA, 0xF)
        tail = random.randint(0, 0xF)
        val = ( head << 8 ) | (body << 4) | tail
        str_a = "%x" % val
        #原来是 return str_a.decode('hex').encode('gb2312') 
        #在Python2.x中经常使用str_obj.decode(‘hex’)在Python3.x中无法使用了。
        #在Python3.x中可以使用codecs.decode(str_obj, ‘hex_codec’)。
        str_b = codecs.decode(str_a,'hex_codec').decode('gb2312')
        return  str_b 


class ImageChar():
    def __init__(self, fontColor = (0, 0, 0),
    size = (100, 40),
    fontPath =sys.path[0]+ '\\Arial Unicode MS.ttf',
    bgColor = (255, 255, 255),
    fontSize = 20):
        self.size = size
        self.fontPath = fontPath
        self.bgColor = bgColor
        self.fontSize = fontSize
        self.fontColor = fontColor
        self.font = ImageFont.truetype(self.fontPath, self.fontSize)
        self.image = Image.new('RGB', size, bgColor)

    def drawText(self, pos, txt, fill):
        draw = ImageDraw.Draw(self.image)
        draw.text(pos, txt, font=self.font, fill=fill)
        del draw    

    def drawTextV2(self, pos, txt, fill, angle=180):
        image=Image.new('RGB', (25,25), (255,255,255))
        draw = ImageDraw.Draw(image)
        draw.text( (0, -3), txt,  font=self.font, fill=fill)
        w=image.rotate(angle,  expand=1)
        self.image.paste(w, box=pos)
        del draw

    def randRGB(self):
        return (0,0,0)

    def randChinese(self, num, num_flip):
        gap = 1
        start = 0
        num_flip_list = random.sample(range(num), num_flip)
        print('num flip list:{0}'.format(num_flip_list))
        char_list = []
        for i in range(0, num):
            char = RandomChar().GB2312()
            char_list.append(char)
            x = start + self.fontSize * i + gap + gap * i
            if i in num_flip_list:
                self.drawTextV2((x, 6), char, self.randRGB())
            else:
                self.drawText((x, 0), char, self.randRGB())
        return char_list, num_flip_list
    def save(self, path):
        self.image.save(path)

def setup_download_dir(directory):
    """
     设置文件夹,文件夹名为传入的 directory 参数,
     若不存在会自动创建
     """
    if not os.path.exists(directory):
        try:
            os.makedirs(directory)
        except Exception as e:
            pass
    return True

def main():
    pic_save_path =sys.path[0]+'\\'+"图片保存目录"
    setup_download_dir(pic_save_path)

    err_num = 0
    for i in range(10):
        try:
            ic = ImageChar(fontColor=(100,211, 90), size=(280,28), fontSize = 25)
            num_flip = random.randint(3,6)
            char_list, num_flip_list = ic.randChinese(10, num_flip)
            for item in   num_flip_list:
                str_timeb =datetime.datetime.now()
                str_aa = str_timeb.strftime('%Y-%m-%d_%H%M%S.')
                str_aa+=str(datetime.datetime.now().microsecond)
                file_path =pic_save_path+'\\'+str_aa+"_"+str(i) +".jpeg" 
                print(file_path)
                ic.save(file_path)
            
        except:
            err_num += 1
            continue
                                                                            


if __name__ == "__main__":
    main()


猜你喜欢

转载自blog.csdn.net/u013628121/article/details/78145657