即時產生 QR 代碼對於行動支付、活動票券與庫存追蹤至關重要。
Aspose.BarCode Cloud SDK for Python 讓您能直接從 Python 應用程式中建立高品質的 QR 代碼。
在本指南中,我們將逐步說明 Aspose.BarCode cloud Python QR 代碼工作流程,從設定憑證到自訂顏色與嵌入標誌。
您還將學習如何批次產生多個代碼以及使用等效的 cURL 命令進行 REST 整合。
Aspose.BarCode cloud Python QR 代碼函式庫亦支援加入標誌並調整錯誤更正等級,以確保掃描的穩定性。
開始之前:先決條件與安裝
開始之前,請確保您具備以下條件:
- 在開發機器上安裝 Python 3.7 或更高版本。
- 擁有包含 client_id 和 client_secret 值的 Aspose Cloud 帳戶。
- 訪問一個資料夾,以保存生成的 PNG 檔案。
使用 pip 安裝 SDK:
pip install aspose-barcode-cloud
下載最新套件並在下載頁面上查看發行說明。
接下來,使用您的憑證配置 API 客戶端(摘自完整腳本):
from asposebarcodecloud import BarCodeApi, ApiClient, Configuration
API_CLIENT_ID = "YOUR_CLIENT_ID"
API_CLIENT_SECRET = "YOUR_CLIENT_SECRET"
config = Configuration()
config.host = "https://api.aspose.cloud"
config.api_key['client_id'] = API_CLIENT_ID
config.api_key['client_secret'] = API_CLIENT_SECRET
barcode_api = BarCodeApi(ApiClient(config))
安裝好 SDK 並設定好憑證後,即可開始產生 QR 代碼。
使用 Aspose.BarCode Cloud SDK for Python 產生自訂 QR 代碼的逐步指南
本分步指南演示如何使用 Aspose.BarCode 雲端 Python QR 代碼 API 生成完全自訂的 QR 圖像。
步驟 1:載入來源文件並設定認證
首先,匯入所需的模組並建立如上所示的 BarCodeApi 實例。這會準備函式庫與 Aspose 雲服務通訊。
第 2 步:定義 QR 代碼參數
建立一個字典,用於保存 QR 代碼的選項,例如類型、文字、格式、顏色和錯誤更正等級。
params = {
"type": "QR",
"text": "https://example.com",
"format": "png",
"foreColor": "Black",
"backColor": "White",
"qrErrorLevel": "LevelQ"
}
有關每個參數的更多詳細資訊,請參閱 BarCode API 參考。
第 3 步:嵌入可選徽標
如果您想添加徽標,請讀取圖像文件,將其轉換為 Base64,然後將其添加到參數中。
def read_logo_as_base64(logo_path: str) -> str:
with open(logo_path, "rb") as logo_file:
return base64.b64encode(logo_file.read()).decode('utf-8')
if logo_path and os.path.isfile(logo_path):
params["logo"] = read_logo_as_base64(logo_path)
此步驟示範 使用 Aspose.BarCode sdk 產生帶有標誌的 QR 代碼 功能。
步驟 4:產生並儲存 QR Code
呼叫 get_barcode_generate 方法,並將返回的位元組寫入檔案。
result_bytes = barcode_api.get_barcode_generate(**params)
with open(output_path, "wb") as out_file:
out_file.write(result_bytes)
print(f"QR code saved to: {output_path}")
步驟 5:批量生成多個 QR 碼(可選)
循環遍歷文字和檔名清單,以一次執行建立多個 QR 代碼。
qr_items = [
{"text": "https://example.com/product/1", "filename": "qr_product_1.png"},
{"text": "Contact: +1-800-555-0199", "filename": "qr_contact.png"}
]
for item in qr_items:
output_file = os.path.join("generated_qrcodes", item["filename"])
generate_qr_code(text=item["text"], output_path=output_file, **common_settings)
此示例在簡潔的迴圈中說明了 批量生成 QR 代碼 Python Aspose。
完整程式碼範例:批次 QR 代碼生成與自訂設定
以下腳本將所有部分組合在一起,展示 Aspose.BarCode cloud Python QR code 生成過程,並支援批次。
import os
import base64
from asposebarcodecloud import BarCodeApi, ApiClient, Configuration, ApiException
# -------------------- Configuration --------------------
# Replace with your actual Aspose Cloud credentials
API_CLIENT_ID = "YOUR_CLIENT_ID"
API_CLIENT_SECRET = "YOUR_CLIENT_SECRET"
config = Configuration()
config.host = "https://api.aspose.cloud"
config.api_key['client_id'] = API_CLIENT_ID
config.api_key['client_secret'] = API_CLIENT_SECRET
# Initialize API instance
barcode_api = BarCodeApi(ApiClient(config))
# -------------------- Helper Functions --------------------
def read_logo_as_base64(logo_path: str) -> str:
"""Read an image file and return its Base64 representation."""
with open(logo_path, "rb") as logo_file:
return base64.b64encode(logo_file.read()).decode('utf-8')
def generate_qr_code(
text: str,
output_path: str,
fore_color: str = "Black",
back_color: str = "White",
error_correction: str = "LevelQ", # Options: LevelL, LevelM, LevelQ, LevelH
logo_path: str = None,
image_format: str = "png"
) -> None:
"""
Generates a QR code with optional customizations and saves it to disk.
"""
try:
# Prepare optional parameters
params = {
"type": "QR",
"text": text,
"format": image_format,
"foreColor": fore_color,
"backColor": back_color,
"qrErrorLevel": error_correction
}
# If a logo is supplied, embed it as a Base64 string
if logo_path and os.path.isfile(logo_path):
params["logo"] = read_logo_as_base64(logo_path)
# Call the Aspose.BarCode Cloud API
result_bytes = barcode_api.get_barcode_generate(**params)
# Write the resulting image to the specified file
with open(output_path, "wb") as out_file:
out_file.write(result_bytes)
print(f"QR code saved to: {output_path}")
except ApiException as e:
print(f"API Exception when generating QR for '{text}': {e}")
# -------------------- Batch Generation Example --------------------
def batch_generate_qr_codes():
"""
Generates multiple QR codes in a loop with varying texts and customizations.
"""
# Sample data for batch processing
qr_items = [
{"text": "https://example.com/product/1", "filename": "qr_product_1.png"},
{"text": "https://example.com/product/2", "filename": "qr_product_2.png"},
{"text": "https://example.com/product/3", "filename": "qr_product_3.png"},
{"text": "Contact: +1-800-555-0199", "filename": "qr_contact.png"},
{"text": "Wi‑Fi: MyNetwork;P:password123;;", "filename": "qr_wifi.png"}
]
# Common customization settings
fore_color = "DarkBlue"
back_color = "LightYellow"
error_correction = "LevelH"
logo_path = "logo.png" # Ensure this file exists in the working directory
output_dir = "generated_qrcodes"
os.makedirs(output_dir, exist_ok=True)
for item in qr_items:
output_file = os.path.join(output_dir, item["filename"])
generate_qr_code(
text=item["text"],
output_path=output_file,
fore_color=fore_color,
back_color=back_color,
error_correction=error_correction,
logo_path=logo_path,
image_format="png"
)
# -------------------- Execution --------------------
if __name__ == "__main__":
batch_generate_qr_codes()
注意: 此程式碼範例示範了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。若遇到任何問題,請參閱官方文件或聯繫支援團隊以獲得協助。
使用 cURL 透過 REST API 生成 QR 代碼
如果您偏好純粹的 REST 方法,您可以使用 Aspose.BarCode cloud Python QR code 端點搭配 cURL 命令來實現相同的結果。
1. 取得存取權杖
curl -X POST "https://api.aspose.cloud/connect/token" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
回應中包含一個 access_token,您將在後續呼叫中使用它。
2. 產生 QR 代碼
替換 YOUR_ACCESS_TOKEN 並根據需要調整查詢參數。
curl -X GET "https://api.aspose.cloud/v3.0/barcode/generate?type=QR&text=HelloWorld&format=png&foreColor=DarkBlue&backColor=LightYellow&qrErrorLevel=LevelH" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o qr_helloworld.png
若要嵌入標誌,首先將圖像轉換為 Base64,然後通過 logo 參數傳遞。
3. 批次生成(迴圈範例)
您可以在 Bash 或 PowerShell 中編寫腳本迴圈,遍歷文字列表,對每個條目呼叫上述 GET 請求,並以不同的檔名保存結果。
欲取得完整的 API 詳細資訊,請參閱 官方 API 文件。
自訂選項:顏色、標誌與錯誤更正
SDK 提供了多個參數,讓您可以自訂 QR 代碼的外觀和韌性。
- foreColor - 設定前景(模組)顏色。範例:
"DarkBlue"。 - backColor - 設定背景顏色。範例:
"LightYellow"。 - qrErrorLevel - 控制錯誤更正等級。可選項為
LevelL、LevelM、LevelQ、LevelH。較高的等級可提升容錯能力,但會降低資料容量。 - logo - 一個 Base64 編碼的影像,將放置於 QR 代碼的中心。
以下是一段程式碼片段,展示了如何在請求字典中組合這些選項:
params = {
"type": "QR",
"text": "https://example.com",
"format": "png",
"foreColor": "DarkBlue",
"backColor": "LightYellow",
"qrErrorLevel": "LevelH",
"logo": read_logo_as_base64("logo.png") # optional
}
調整數值以符合您的品牌指南或視覺設計需求。
您可能有的問題
-
如何在不編寫大量代碼的情況下使用 Aspose.BarCode Python 創建自訂 QR 代碼?
SDK 抽象了繁重的工作。只需在params字典中設定少量參數並呼叫get_barcode_generate,即可獲得可直接使用的 QR 圖像。 -
是否可以在無伺服器平台上使用 Aspose.BarCode SDK 生成帶有標誌的 QR 代碼?
是的。只要執行環境能夠連接https://api.aspose.cloud,該庫即可在任何 Python 環境中運行,包括 AWS Lambda 或 Azure Functions。 -
Python 腳本用於 QR 代碼生成 Aspose 會返回什麼?
get_barcode_generate方法返回原始圖像位元組,您可以直接寫入檔案或串流到 Web 回應。 -
如何為我的品牌調色板自訂 Aspose.BarCode Python 的 QR 代碼顏色?
使用foreColor和backColor參數,搭配 API 支援的任何 HTML 顏色名稱或 HEX 值。 -
授權選項有哪些,我該如何取得臨時授權?
完整授權可於 Aspose 官方網站購買。若需評估,您可以從temporary license page申請臨時授權。