Python生成一維碼,二維碼

2021-02-13 Django學堂

 

我們的生活已完全離不開一維碼和二維碼,本文會簡單的介紹如果通過python的方法來生成它們

 

本文環境:

Python 2.7.10

pyBarcode==0.7

Pillow==5.1.0


 

pip install pyBarcode

pip install Pillow

 

(env) python manage.py shell

Python 2.7.10 (default, May 23 2015, 09:40:32)[MSC v.1500 32 bit (Intel)] on win32

Type "help", "copyright","credits" or "license" for more information.

(InteractiveConsole)

>>> from barcode.writer importImageWriter

>>> from barcode.codex import Code39

>>> from PIL import Image, ImageDraw,ImageFont, ImageWin

>>> imagewriter = ImageWriter()

>>> ean =Code39("1234567890", writer=imagewriter, add_checksum=False)

>>> fullname = ean.save('image')

>>> img = Image.open(fullname)

>>> img.show()

 

首先我們導入Code39,pyBarcode支持多種方式,可用下面命令獲取

 

>>> import barcode

>>> barcode.PROVIDED_BARCODES

['code39', 'ean', 'ean13', 'ean8', 'gs1','gtin', 'isbn', 'isbn10', 'isbn13', 'issn', 'jan', 'pzn', 'upc', 'upca']

 

add_checksum 表示是否將checksum添加到code中

 

ean.save()參數為文件名,這個文件名可以是絕對路徑或者相對路徑。

 

最後,調用了PIL的Image來顯示這個生成的圖片,如下:

  

 

>>> from StringIO import StringIO

>>> i = StringIO()

>>> ean =Code39("0987654321", writer=imagewriter, add_checksum=False)

>>> ean.write(i)

>>> f = StringIO(i.getvalue())

>>> img1 = Image.open(f)

>>> print 'save to StringIO and showwith image format'

save to StringIO and show with image format

>>> img1.show()

 

圖片打開時是從StringIO中把內容讀出來。

 

 

從上面圖片效果看,文字離一維碼距離實在太遠了,需要調整一下。差了一下,基本的Writer有下面選項,還有繼承類的SVGWritr和ImageWriter等,對我的需要來說,基本的就夠了,可以通過調整text_distance和font_size來調整效果

 

module_width:

The width of one barcode module in mm  as float. Defaults to 0.2.

module_height:

The height of the barcode modules in  mm as float. Defaults to 15.0.

quiet_zone:

Distance on the left and on the right  from the border to the first (last) barcode module in mm as float.  Defaults to 6.5.

font_size:

Font size of the text under the  barcode in pt as integer. Defaults to 10.

text_distance:

Distance between the barcode and the  text under it in mm as float. Defaults to 5.0.

background:

The background color of the created  barcode as string. Defaults to white.

foreground:

The foreground and text color of the  created barcode as string. Defaults to black.

center_text:

If true (the default) the text is  centered under the barcode else left aligned.

 

有兩種方法可以將這個選項參數傳遞給Writer

All writer take the following options(specified as keyword arguments to Barcode.save(filename, option=value) or setvia Writer.set_options(option=value)).

 

實際使用中,Writer.set_options並沒有生效,不確定是否我的方法用錯了。

options = {"text_distance":1, "font_size":12}
imagewriter = ImageWriter()
imagewriter.set_options(options=options)

 

改用Barcode.save方法

options = {"text_distance":1,"font_size":12}
ean = Code39(filename, writer=imagewriter,add_checksum=False)
ean.save(fullpath,options=options)

 

圖片效果如下

 

詳細內容可查看https://pythonhosted.org/pyBarcode/writers/index.html

 

pip install qrcode

 

 

定義二維碼生成函數,將網址放入二維碼是常用場景,我們就以這個為例

 

在qrcode.QRCode初始化函數裡,可以定義相應參數,官方資料非常吝嗇,下面是網上找到的一些用法

 

defgen_qrcode(link):
   qr=qrcode.QRCode(
        version =2,
        error_correction =qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=10,)
   qr.add_data(link)
   qr.make(fit=True)
   img = qr.make_image()
   img.show()

   photopath = os.path.join(settings.MEDIA_ROOT,"test")
   ifnot os.path.exists(photopath):
       os.makedirs(photopath)
   path = os.path.join(photopath,'create.jpg')
   img.save(path)
   return path

 

生成的圖片如下

 

暫時不會,哈哈

關注下方公眾號獲取更多文章

參考文檔

pyBarcode 0.7https://pypi.python.org/pypi/pyBarcode

Pillow-4.2.1https://pypi.python.org/pypi/Pillow

pywin32https://pypi.python.org/pypi/pywin32/

https://pycode.readthedocs.io/en/latest/

https://pythonhosted.org/pyBarcode/index.html

相關焦點

  • 是誰發明了二維碼?一維碼又是什麼鬼?
    一維碼就是條形碼,它出現於20世紀20年代,誕生在美國西屋電氣公司的實驗室裡,這是一家世界著名的電工設備製造企業。由於高精度的汽車零配件需要匹配很多信息,傳統的條形碼已經無法滿足公司的需要,於是騰弘原帶領團隊研究出了二維碼。
  • Python學習:mac電腦安裝python教程
    與python2.7 共存2 下載安裝包進入官方安裝包下載頁面,https://www.python.org/downloads/mac-osx/找到合適的安裝包,基本上mac電腦都是64位的系統,因此選擇64位的安裝包進行下載
  • python黑知識:python本體
    講述python的實現本體,版本,構建時間,構建工具和構建參數python的實現有很多種,如果想研究一下它語言本身一些機制的實現,可能需要看原始碼,那麼,就需要找到相應的實現,分支和版本。目前使用的python實現,根據python實現存在有這幾種CPython, Stackless Python, MicroPython, CLPython, Cython, IronPython, Jython, Pyjs, PyPy, Numba, Shed Skin Nuitka ,可以說是讓人眼花繚亂。
  • python基礎學習教程:Python基礎語法
    >>> '''在學習過程中有什麼不懂得可以加我的python學習交流扣扣qun,934109170群裡有不錯的學習教程、開發工具與電子書籍。與你分享python企業當下人才需求及怎麼從零基礎學習好python,和學習什麼內容。'''Window 上在安裝 Python 時已經安裝了交互式編程客戶端,提示窗口如下:
  • Python 進階必備:圖像庫 pillow
    您可以使用此模塊創建新圖像、注釋或修改現有圖像,以及動態生成圖形以供web使用。ImageGrabImageGrab模塊可用於將屏幕或剪貼板的內容複製到PIL圖像內存。ImageFilterImageFilter模塊包含一組預定義的濾鏡,可以與Image.filter()方法一起使用。ImageColorImageColor模塊包含顏色表和從css3風格的顏色說明符到RGB元組的轉換器。
  • Python 情人節告白特技:隱藏在聊天記錄裡的珍貴禮物
    生成詞雲!!二、根據第一步得到的聊天數據生成詞雲1. 導入我們的聊天記錄,並對每一行進行分詞聊天記錄是一行一行的句子,我們需要使用分詞工具把這一行行句子分解成由詞語組成的數組,這時候我們就需要用到結巴分詞了。
  • 有趣且鮮為人知的 Python 特性,火了!
    項目地址為:https://github.com/leisurelicht/wtfpython-cn來體會一些難以理解和反人類直覺的Python特性吧!引用自 https://docs.python.org/3/c-api/long.html可以再看看這個案例:>>> id(256)10922528>>> a = 256>>> b = 256>>> id(a)10922528>&
  • 表白二維碼:教你製作自定義文字+音樂的背景圖二維碼
    快手網紅八卦、免費看vip電影hello,大家好,小編前一段時間分享了一些有趣的文字加音樂的二維碼,很多粉絲問小編怎麼製作的,今天小編就詳細給大家講解一下
  • Python詞雲:Windows安裝Wordcloud報錯解決辦法
    首先,先看清楚你的python版本,以及搞清楚你的python是基於32位系統還是64位系統。具體操作方法:1、 在左下角搜索windows搜索框裡輸入cmd,打開命令行窗口;2、 輸入python;3、 這裡可以看到python的版本是3.8.2,基於32位系統。
  • Python爬蟲實戰:爬取天氣數據的實例詳解
    在本篇文章裡小編給大家整理的是一篇關於python爬取天氣數據的實例詳解內容,有興趣的朋友們學習下。
  • Python 炫技操作:五種 Python 轉義表示法
    舉個例子>>> msg = "hello\013world\013hello\013python">>> print(msg)hello     world          hello               python>>> 是不是有點神奇
  • Python炫技操作:花式導包的八種方法
    /os.pyc'>>>> myos.getcwd()'/home/wangbm'從 python 3 開始,內建的 reload 函數被移到了 imp 模塊中。語法如下:execfile(filename[, globals[, locals]])參數有這麼幾個:>>> execfile("/usr/lib64/python2.7/os.py")>>> >>> getcwd()'/home/wangbm'
  • 《流暢的Python》微信抽獎程序
    看看誰中獎啦:❯ python mp.py 輸入幸運數字❯ 85如下5位同學獲得《流暢的Python》:用戶: Mr.Ran    樓層: 254   參與時間: 2017-06-06 00:43:21  評論內容:人生苦短,我學Python 85用戶: 木木杉       樓層: 184
  • 教學黑科技:免費生成在線遊戲,一鍵轉發給學生玩
    Step6: 來看看第一個Words能生成什麼遊戲,以及怎麼操作。     把單詞都輸入完後,往下拉,就可以看到生成的遊戲,輸入一次內容,在這個words遊戲大類下就生成了3個小遊戲:word search(找單詞),hangman(吊死鬼),Anagrams(拼單詞)。
  • 新門牌帶二維碼
    細心的街坊發現,新門牌上除了門牌號等信息外,還有一個二維碼。與傳統門牌相比,這種帶二維碼的「智慧」門牌有哪些功能呢?作為試點,中心城區東華路安裝了「智慧」門牌。用手機掃一掃門牌上的二維碼,就會看到房屋坐標、編號等信息。
  • 二維碼「掃一掃」騙局,5大套路要警惕!
    二維碼「掃一掃」主要套路有以下5種:一些不法分子通過贈送小禮品的方式,誘導人們掃描二維碼進行註冊並填寫手機號、身份證號等信息,隨後便將這些信息與資料打包賣給一些「推銷」公司或詐騙分子。不法分子製造附有二維碼的假繳費單(水、電、燃氣費)、交通罰單,顯示掃碼即可繳費,誤導人們掃碼,從而實施詐騙。
  • Python的數據可視化:對比7種工具包
    Python部落(python.freelycode.com)組織翻譯,禁止轉載,歡迎轉發。
  • 來自16 歲高中生的暴擊: Python3.9 的「新特性必知圖」火了
    此外,還有cancel_futures。參考連結:https://docs.python.org/zh-cn/3.9/whatsnew/3.9.htmlhttps://twitter.com/PrasoonPratham/status/1313392420038483968
  • 譯詞 | 「二維碼」為什麼譯為 QR code?
    二維碼在生活中的應用越來越廣泛掃碼支付掃碼加好友掃碼得紅包都會用到下面這種方塊形的二維碼