import gradio as gr import io from PIL import Image import barcode from barcode.writer import ImageWriter import qrcode from pylibdmtx import encode def generate_barcode(barcode_type, data): if barcode_type == 'EAN13': try: ean = barcode.get('ean13', data, writer=ImageWriter()) except Exception as e: return f"Error: {e}" buffer = io.BytesIO() ean.write(buffer) buffer.seek(0) img = Image.open(buffer) return img elif barcode_type == 'QR Code': img = qrcode.make(data) return img elif barcode_type == 'DataMatrix': try: encoded = encode(data.encode('utf-8')) except Exception as e: return f"Error: {e}" buffer = io.BytesIO(encoded.png) img = Image.open(buffer) return img else: return "Unsupported barcode type." with gr.Blocks() as demo: gr.Markdown("### 條碼生成器 (EAN13, QR Code, DataMatrix)") barcode_type = gr.Radio(['EAN13', 'QR Code', 'DataMatrix'], value='EAN13', label="選擇條碼格式") data_input = gr.Textbox(label="輸入條碼內容", value="123456789012") output = gr.Image(label="生成的條碼") error_msg = gr.Textbox(visible=False, interactive=False) def on_generate(barcode_type, data): result = generate_barcode(barcode_type, data) if isinstance(result, str): # error message error_msg.visible = True error_msg.value = result return None else: error_msg.visible = False error_msg.value = "" return result data_input.change(on_generate, [barcode_type, data_input], output) barcode_type.change(on_generate, [barcode_type, data_input], output) demo.launch()