Spaces:
Paused
Paused
File size: 2,592 Bytes
dae6eac 556cb08 dae6eac 182495d dae6eac 182495d dae6eac 182495d dae6eac 182495d dae6eac 182495d 556cb08 182495d 556cb08 182495d 556cb08 dae6eac 182495d dae6eac 182495d dae6eac 182495d dae6eac 182495d dae6eac 182495d dae6eac 182495d dae6eac |
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
import gradio as gr
from PIL import Image
import os
import base64
import io
def add_logo_base64(image_base64, logo_size_percent=20, margin_percent=2):
"""
Add logo to image provided as base64 string
Args:
image_base64: Base64 encoded image string (with or without data URL prefix)
logo_size_percent: Size of logo as percentage of main image width (default 20%)
margin_percent: Margin from edges as percentage of main image width (default 2%)
"""
if not image_base64:
return None
# Handle base64 input
if image_base64.startswith('data:image'):
# Remove data URL prefix
base64_str = image_base64.split(',')[1]
else:
base64_str = image_base64
# Decode base64 to image
try:
image_data = base64.b64decode(base64_str)
main_image = Image.open(io.BytesIO(image_data))
except Exception as e:
return f"Error decoding image: {str(e)}"
# Load the logo
logo_path = "logo.png"
if not os.path.exists(logo_path):
# Return original as base64 if logo not found
return image_base64
# Open logo
logo = Image.open(logo_path).convert("RGBA")
# Convert main image to RGBA to support transparency
main_img = main_image.convert("RGBA")
# Calculate logo size (maintain aspect ratio)
logo_width = int(main_img.width * logo_size_percent / 100)
logo_height = int(logo.height * (logo_width / logo.width))
# Resize logo
logo = logo.resize((logo_width, logo_height), Image.Resampling.LANCZOS)
# Calculate position (top-right corner with margin)
margin = int(main_img.width * margin_percent / 100)
x_position = main_img.width - logo_width - margin
y_position = margin
# Create a copy of the main image
result = main_img.copy()
# Paste logo with transparency
result.paste(logo, (x_position, y_position), logo)
# Convert back to RGB
result = result.convert("RGB")
# Convert result to base64
buffered = io.BytesIO()
result.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode()
return f"data:image/png;base64,{img_base64}"
# Create simple interface for API
iface = gr.Interface(
fn=add_logo_base64,
inputs=gr.Textbox(label="Image Base64", placeholder="Paste base64 encoded image here"),
outputs=gr.Textbox(label="Result Base64"),
title="Logo Adder API",
description="Send base64 encoded image to add logo"
)
if __name__ == "__main__":
iface.launch() |