File size: 1,806 Bytes
21baa9f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 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()
|