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']
"""
#生成一維碼啰挪,參數(shù):碼類型亦歉、碼內容玉工、文件名(文件名后綴自動加.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的方式合并存成一張圖籍胯,參數(shù):碼類型裁赠、文件數(shù)量
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')
#主函數(shù)設置需要生成碼類型的目錄强法,生成相應碼制肮。
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作為實例展示效果為: