Spaces:
Running
Running
| import gradio as gr | |
| from PIL import Image | |
| import rembg | |
| import io | |
| def process_image(image, outline_size): | |
| if image is None: | |
| return None | |
| # Convert image to bytes for rembg | |
| img_byte_arr = io.BytesIO() | |
| image.save(img_byte_arr, format="PNG") | |
| img_byte_arr.seek(0) | |
| # Remove background | |
| processed_bytes = rembg.remove(img_byte_arr.getvalue()) | |
| processed_img = Image.open(io.BytesIO(processed_bytes)).convert("RGBA") | |
| # Add white outline if selected | |
| if outline_size > 0: | |
| # Create a larger background image with white color | |
| background = Image.new( | |
| "RGBA", | |
| ( | |
| processed_img.width + 2 * outline_size, | |
| processed_img.height + 2 * outline_size, | |
| ), | |
| (255, 255, 255, 0), # White with alpha=0 for transparency | |
| ) | |
| # Paste the processed image onto the background | |
| background.paste(processed_img, (outline_size, outline_size), processed_img) | |
| # Draw a white outline around the image | |
| pixels = background.load() | |
| for x in range(background.width): | |
| for y in range(background.height): | |
| if x < outline_size or y < outline_size or x >= background.width - outline_size or y >= background.height - outline_size: | |
| pixels[x, y] = (255, 255, 255, 255) # White with alpha=255 for visibility | |
| final_img = background | |
| else: | |
| final_img = processed_img | |
| # Save the result as bytes for Gradio | |
| output_buffer = io.BytesIO() | |
| final_img.save(output_buffer, format="PNG") | |
| output_buffer.seek(0) | |
| return final_img, output_buffer # Return image and buffer for download | |
| # Gradio Interface | |
| with gr.Blocks(title="Sticker Maker") as interface: | |
| gr.Markdown("# Sticker Maker") | |
| gr.Markdown("Upload an image to remove the background and optionally add a white outline.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| image_upload = gr.Image(label="Upload Image", type="pil") | |
| outline_size = gr.Slider( | |
| label="Outline Thickness", minimum=0, maximum=20, value=5, step=1 | |
| ) | |
| create_btn = gr.Button("Create Sticker", variant="primary") | |
| with gr.Column(): | |
| output_image = gr.Image(label="Preview", type="pil", interactive=False) | |
| download_file = gr.File(label="Download Sticker as PNG") | |
| # Process image and allow direct download from preview pane | |
| create_btn.click( | |
| fn=process_image, | |
| inputs=[image_upload, outline_size], | |
| outputs=[output_image, download_file], | |
| ) | |
| if __name__ == "__main__": | |
| interface.launch(debug=True) | |