Spaces:
Runtime error
Runtime error
import gradio as gr | |
import qrcode | |
def generate_qrcode(url, color, gradient, gradient_colors, border_radius, logo): | |
qr = qrcode.QRCode( | |
version=1, | |
error_correction=qrcode.constants.ERROR_CORRECT_H, | |
box_size=10, | |
border=4, | |
) | |
qr.add_data(url) | |
qr.make(fit=True) | |
qr_image = qr.make_image(fill_color=color, back_color="white") | |
if gradient: | |
qr_image = qr_image.convert("RGB") | |
width, height = qr_image.size | |
gradient_color1, gradient_color2 = gradient_colors | |
for i in range(height): | |
shift = int((i / height) * 255) | |
fill_color = tuple(int(gradient_color1[c] + shift * (gradient_color2[c] - gradient_color1[c]) / 255) for c in range(3)) | |
for j in range(width): | |
pixel = qr_image.getpixel((j, i)) | |
if pixel == (0, 0, 0): | |
qr_image.putpixel((j, i), fill_color) | |
if border_radius > 0: | |
qr_image = qr_image.resize((qr_image.size[0] + border_radius*2, qr_image.size[1] + border_radius*2)) | |
qr_image = qr_image.convert("RGBA") | |
width, height = qr_image.size | |
border_radius = max(1, min(border_radius, int(width/2), int(height/2))) | |
mask = Image.new('L', (width, height), 0) | |
draw = ImageDraw.Draw(mask) | |
draw.ellipse((0, 0, 2*border_radius, 2*border_radius), fill=255) | |
draw.ellipse((width-2*border_radius, 0, width, 2*border_radius), fill=255) | |
draw.ellipse((0, height-2*border_radius, 2*border_radius, height), fill=255) | |
draw.ellipse((width-2*border_radius, height-2*border_radius, width, height), fill=255) | |
alpha = Image.new('L', (width, height), int(255 * 0.5)) | |
qr_image.paste(alpha, (0, 0), mask) | |
if logo is not None: | |
logo_image = Image.open(logo).convert("RGBA") | |
qr_image.paste(logo_image, (int((qr_image.size[0] - logo_image.size[0]) / 2), int((qr_image.size[1] - logo_image.size[1]) / 2)), logo_image) | |
qr_image.save("qr_code.png") | |
return "qr_code.png" | |
iface = gr.Interface( | |
fn=generate_qrcode, | |
inputs=[ | |
gr.inputs.Textbox(label="URL"), | |
gr.ColorPicker(label="Color"), | |
gr.inputs.Checkbox(label="Gradient"), | |
gr.ColorPicker(label="Gradient Colors", n_colors=2), | |
gr.inputs.Number(label="Border Radius"), | |
gr.inputs.File(label="Logo") | |
], | |
outputs="image", | |
title="QR Code Generator", | |
description="Enter a URL and customize the QR code appearance", | |
examples=[ | |
["instagram.com", "#FF0000", True, ["#FF0000", "#0000FF"], 10, None], | |
["twitter.com", "#00FF00", False, [], 0, "logo.png"], | |
["huggingface.co", "#0000FF", True, ["#FF0000", "#00FF00"], 15, "logo.png"] | |
] | |
) | |
iface.launch() | |