Spaces:
Sleeping
Sleeping
Update app.py
Browse files12234567781091011131415161718192021222324121314262728293031151633343536373839404142434445464748495051525354555657585960611718192021226465666768232425262771282973747576303132333435import gradio as grfrom PIL import Image, ImageChops, ImageFilterfrom PIL import Imageimport rembgimport ioimport tempfileimport osimport zipfile
def remove_background(image): """Remove background using rembg (fixed bytes handling)""" # Process image img_byte_arr = io.BytesIO() image.save(img_byte_arr, format='PNG') result_bytes = rembg.remove(img_byte_arr.getvalue()) # Process bytes directly return Image.open(io.BytesIO(result_bytes)).convert("RGBA")
def add_outline(image, outline_width=2, outline_color=(255, 255, 255)): """Add white outline to transparent image""" alpha = image.split()[-1] dilated_alpha = alpha.filter(ImageFilter.MaxFilter(outline_width * 2 + 1)) outline_mask = ImageChops.difference(dilated_alpha, alpha) # Create outline layer outline = Image.new('RGBA', image.size, (*outline_color, 255)) outline.putalpha(outline_mask) result_bytes = rembg.remove(img_byte_arr.getvalue()) processed_img = Image.open(io.BytesIO(result_bytes)).convert("RGBA") # Combine layers final = Image.alpha_composite(outline, image) return final
def process_images(image_files): # Create temporary directory # Save to temporary file for download temp_dir = tempfile.mkdtemp() try: processed_paths = [] for i, img_file in enumerate(image_files): # Process image img = Image.open(img_file.name).convert("RGBA") no_bg = remove_background(img) sticker = add_outline(no_bg) # Save to temporary file file_path = os.path.join(temp_dir, f"sticker_{i+1}.png") sticker.save(file_path) processed_paths.append(file_path) # Return single file or ZIP if len(processed_paths) == 1: return processed_paths[0] else: zip_path = os.path.join(temp_dir, "stickers.zip") with zipfile.ZipFile(zip_path, 'w') as zipf: for p in processed_paths: zipf.write(p, os.path.basename(p)) return zip_path except Exception as e: # Cleanup on error for p in processed_paths: try: os.remove(p) except: pass raise e file_path = os.path.join(temp_dir, "no_background.png") processed_img.save(file_path) return processed_img, file_path
# Gradio Interfaceimage_upload = gr.File(label="Upload Images (Single or Batch)", file_types=["image"], file_count="multiple")
output = gr.File(label="Download Sticker(s)")image_upload = gr.Image(label="Upload Image", type="pil")output_preview = gr.Image(label="Preview", type="pil")output_file = gr.File(label="Download PNG")
interface = gr.Interface( fn=process_images, fn=remove_background, inputs=image_upload, outputs=output, title="✨ Sticker Maker", description="Remove background, add white outline, and download as PNG(s)", allow_flagging="never" outputs=[output_preview, output_file], title=" PNG Background Remover", description="Remove background and preview/download as transparent PNG",)
if __name__ == "__main__":app.py+16-60