一、python 生成一维码

来源:互联网 发布:父母洗脑 知乎 编辑:程序博客网 时间:2024/05/07 05:25

生活中到处可见一维码,几乎所有的正规产品上都可以看到,这几天好奇使用python可不可以实现生成一维码,并打印的功能,还真让我找到方法了,下面记录一下过程。

所需软件:
pyBarcode 0.7 https://pypi.python.org/pypi/pyBarcode/0.7
python2.7.12
Pillow-4.2.1 https://pypi.python.org/pypi/Pillow/4.2.1
pywin32 https://pypi.python.org/pypi/pywin32/

第一步 生成一维码:

from barcode.writer import ImageWriterfrom barcode.codex import Code39from PIL import Image, ImageDraw, ImageFont, ImageWinfrom StringIO import StringIOdef generagteBarCode(self):        imagewriter = ImageWriter()        #保存到图片中        # add_checksum : Boolean   Add the checksum to code or not (default: True)        ean = Code39("1234567890", writer=imagewriter, add_checksum=False)        # 不需要写后缀,ImageWriter初始化方法中默认self.format = 'PNG'        print '保存到image2.png'        ean.save('image2')        img = Image.open('image2.png')        print '展示image2.png'        img.show()        # 写入stringio流中        i = StringIO()        ean = Code39("0987654321", writer=imagewriter, add_checksum=False)        ean.write(i)        i = StringIO(i.getvalue())        img1 = Image.open(i)        print '保存到stringIO中并以图片方式打开'        img1.show()

效果如下:
输入图片说明

参考文章:
pyBarcode document http://pythonhosted.org/pyBarcode/writers/index.html
StringIO https://docs.python.org/2/library/stringio.html
pywin32 win32print http://timgolden.me.uk/python/win32_how_do_i/print.html
pillow document http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#example-draw-a-gray-cross-over-an-image
pillow 图片处理示例 http://www.yeayee.com/article-6739499-1.html

原创粉丝点击