Spaces:
Sleeping
Sleeping
File size: 2,676 Bytes
a7a2a27 1cdc356 a7a2a27 1cdc356 04baf73 a7a2a27 1cdc356 1071bed 1cdc356 a7a2a27 04baf73 1cdc356 04baf73 1cdc356 04baf73 a7a2a27 1cdc356 138cf8b a7a2a27 1cdc356 a7a2a27 1cdc356 a7a2a27 1cdc356 a7a2a27 1cdc356 a7a2a27 1cdc356 a7a2a27 |
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 |
import gradio as gr
import numpy as np
from PIL import Image
def overlay_images(x, y, scale, design_img, target_img):
# Convert inputs to PIL images
design_image = Image.fromarray(design_img).convert("RGBA")
target_image = Image.fromarray(target_img).convert("RGBA")
# Resize the design image based on scale
design_image = design_image.resize(
(int(design_image.width * scale), int(design_image.height * scale)), Image.Resampling.LANCZOS
)
# Ensure the design image has an alpha channel for transparency
if design_image.mode != 'RGBA':
design_image = design_image.convert('RGBA')
# Create a transparent overlay
overlay = Image.new('RGBA', target_image.size, (255, 255, 255, 0))
overlay.paste(design_image, (x, y), design_image)
# Combine overlay with target image
combined = Image.alpha_composite(target_image, overlay)
return np.array(combined)
with gr.Blocks() as editor:
gr.Markdown("## Drag-and-Drop Image Editor with Resizing")
with gr.Row():
design_img = gr.Image(label="Design Image", type="numpy")
target_img = gr.Image(label="Target Image", type="numpy")
overlay_result = gr.Image(label="Overlay Result")
# Hidden elements to hold drag-drop coordinates and scale
x_coord = gr.Number(value=0, visible=False)
y_coord = gr.Number(value=0, visible=False)
scale_factor = gr.Number(value=1.0, visible=False)
apply_overlay = gr.Button("Apply Overlay")
# JavaScript for dragging and resizing
custom_js = """
<script>
let img = document.querySelector('img[data-target="design_img"]');
let result = document.querySelector('img[data-target="overlay_result"]');
let xInput = document.querySelector('input[name="x_coord"]');
let yInput = document.querySelector('input[name="y_coord"]');
let scaleInput = document.querySelector('input[name="scale_factor"]');
img.draggable = true;
img.ondragstart = function(event) {
event.dataTransfer.setDragImage(new Image(), 0, 0);
};
img.ondragend = function(event) {
let rect = result.getBoundingClientRect();
xInput.value = event.clientX - rect.left;
yInput.value = event.clientY - rect.top;
};
let resizeObserver = new ResizeObserver(entries => {
scaleInput.value = img.width / img.naturalWidth;
});
resizeObserver.observe(img);
</script>
"""
html_code = gr.HTML(custom_js)
# Load the overlayed image on clicking the button
apply_overlay.click(overlay_images, [x_coord, y_coord, scale_factor, design_img, target_img], overlay_result)
editor.launch()
|