使用python-barcode生成一维码
1.安装python包
pip install Pillow
pip install python-barcode
2.实例程序
# -*- coding: utf-8 -*-import barcode
import random
from barcode.writer import ImageWriter
import os
from PIL import Image#生成一维码的类型的种类
"""
[u'code39', u'code128', u'ean', u'ean13', u'ean8', u'gs1', u'gtin',u'isbn', u'isbn10', u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
"""#生成一维码,参数:码类型、码内容、文件名(文件名后缀自动加.png)
def barcode_to_png(barcode_type,text_str,filename):EAN = barcode.get_barcode_class(barcode_type) #设置生成一维码的类型ean = EAN(text_str, writer=ImageWriter())ean.save(filename)#8个一维码进行2*4的方式合并存成一张图,参数:码类型、文件数量
def barcode_fun(barcode_type,file_num):for i in range(8*file_num):r_num = random.randint(100000000000000, 999999999999999)barcode_to_png(barcode_type,str(r_num),'./code/'+barcode_type+'/'+str(i))if( (i+1)%8 == 0 ):base_img0 = Image.open('./code/'+barcode_type+'/'+str(i-7)+'.png')base_img1 = Image.open('./code/'+barcode_type+'/'+str(i-6)+'.png')base_img2 = Image.open('./code/'+barcode_type+'/'+str(i-5)+'.png')base_img3 = Image.open('./code/'+barcode_type+'/'+str(i-4)+'.png')base_img4 = Image.open('./code/'+barcode_type+'/'+str(i-3)+'.png')base_img5 = Image.open('./code/'+barcode_type+'/'+str(i-2)+'.png')base_img6 = Image.open('./code/'+barcode_type+'/'+str(i-1)+'.png')base_img7 = Image.open('./code/'+barcode_type+'/'+str(i)+'.png')x = base_img0.size[0]y = base_img0.size[1]target = Image.new('RGBA', (2*x,4*y), color=0)target.paste(base_img0,(0,0,x,y))target.paste(base_img1,(x,0,2*x,y))target.paste(base_img2,(0,y,x,2*y))target.paste(base_img3,(x,y,2*x,2*y))target.paste(base_img4,(0,2*y,x,3*y))target.paste(base_img5,(x,2*y,2*x,3*y))target.paste(base_img6,(0,3*y,x,4*y))target.paste(base_img7,(x,3*y,2*x,4*y))target.save('./code/'+barcode_type+'/'+barcode_type+"_"+str((i+1)/8)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i-7)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i-6)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i-5)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i-4)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i-3)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i-2)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i-1)+'.png')os.system("rm "+'./code/'+barcode_type+'/'+str(i)+'.png')#主函数设置需要生成码类型的目录,生成相应码。
if __name__=="__main__":os.system("mkdir -p ./code")os.system("mkdir -p ./code/code128")os.system("mkdir -p ./code/EAN13")os.system("mkdir -p ./code/code39")os.system("mkdir -p ./code/upca")code128 = 'code128'ean13 = 'EAN13'code39 = 'code39'upca = 'upca'barcode_fun(code128,10)barcode_fun(ean13,10)barcode_fun(code39,10)barcode_fun(upca,10)
3.结果
在当前目录下的code目录下生成了相应的目录和文件
code128_1.png作为实例展示效果为: