二維碼已成為當今數位世界的重要工具,彌合了實體空間和數位空間之間的差距。無論您是要分享網站連結、聯絡訊息,甚至是 Wi-Fi 憑證,二維碼都可以輕鬆實現。在本文中,我們將深入研究基於 Python 的 QR 碼產生器,逐步解釋程式碼,並向您展示如何建立自己的自訂 QR 碼。讓我們開始吧!
Python 是一種多功能程式語言,可輕鬆實現任務自動化,包括產生 QR 碼。只需幾行程式碼,您就可以建立不僅實用而且美觀的二維碼。最好的部分?您可以自訂顏色和尺寸以配合您的品牌或個人風格。
下面,我們將引導您完成產生二維碼的 Python 程式碼,並解釋如何有效地使用它。
開始之前,您需要安裝必要的 Python 程式庫。開啟終端機或 Jupyter Notebook 並執行以下命令:
!pip install qrcode[pil]
此指令安裝 qrcode 函式庫(用於產生 QR 碼)和 PIL(Pillow),用於處理影像處理。
安裝程式庫後,在 Python 腳本或筆記本中匯入必要的模組:
import qrcode from PIL import Image from IPython.display import display
接下來,我們定義一個名為generate_qr_code的函數,它接受三個參數:
這是函數:
def generate_qr_code(link, fill_color='black', back_color='white'): """ Generates a QR code from the given link and displays it in the notebook. :param link: The URL or text to encode in the QR code. :param fill_color: The color of the QR code (default is 'black'). :param back_color: The background color of the QR code (default is 'white'). """ # Create a QR code instance qr = qrcode.QRCode( version=1, # Controls the size of the QR Code (1 is the smallest, 40 is the largest) error_correction=qrcode.constants.ERROR_CORRECT_L, # Error correction level box_size=10, # Size of each box in the QR code border=4, # Border size around the QR code ) # Add data to the QR code qr.add_data(link) qr.make(fit=True) # Create an image from the QR code instance img = qr.make_image(fill_color=fill_color, back_color=back_color) # Display the image in the notebook display(img)
要產生二維碼,只要呼叫generate_qr_code函數即可。具體方法如下:
!pip install qrcode[pil]
讓我們分解程式碼的關鍵組成:
QRCode 實例:qrcode.QRCode 類別用於建立 QR 碼物件。您可以自訂其大小、糾錯等級和邊框。
新增資料:add_data 方法將提供的連結或文字編碼到二維碼中。
建立影像:make_image 方法將 QR 碼產生為影像,並具有可自訂的顏色。
顯示圖片:顯示功能直接在 Jupyter Notebook 中顯示二維碼。
這個二維碼產生器的最佳功能之一是它的靈活性。您可以:
以下是使用此二維碼產生器的一些方法:
使用 Python 產生二維碼簡單、快速且高度可自訂。使用本文提供的程式碼,您可以出於任何目的(無論是個人目的還是專業目的)建立 QR 碼。那為什麼還要等呢?立即開始產生您自己的二維碼並開啟一個充滿無限可能的世界!
專業提示:為本文加書籤以供日後參考,並與可能覺得有用的朋友分享。快樂編碼! ?
!pip install qrcode[pil]
作者學分:
使用工具和技術學習化學工程師計算
以上是使用 Python 在幾秒鐘內創建令人驚嘆的 QR 碼 - 方法如下!的詳細內容。更多資訊請關注PHP中文網其他相關文章!