ZainMalik0925's picture
Update app.py
59f927f verified
import streamlit as st
from PIL import Image
import requests
from io import BytesIO
# Function to remove background using Remove.bg API
def remove_background(image: Image.Image, api_key: "YcbUJiVwip7VEeH7vJJdtK5o") -> Image.Image:
# Convert image to bytes
buffered = BytesIO()
image.save(buffered, format="PNG")
buffered.seek(0)
# API request
response = requests.post(
"https://api.remove.bg/v1.0/removebg",
files={"image_file": buffered},
data={"size": "auto"},
headers={"X-Api-Key": api_key},
)
if response.status_code == 200:
output_image = Image.open(BytesIO(response.content))
return output_image
else:
error_message = response.json().get("errors", [{}])[0].get("detail", "Unknown error")
raise Exception(f"Remove.bg API error: {response.status_code} - {error_message}")
# Function to compress or resize the image if it exceeds 22MB
def resize_image(image: Image.Image, max_size: int = 22 * 1024 * 1024) -> Image.Image:
# Compress or resize the image until it is under the max size limit
output_buffer = BytesIO()
image.save(output_buffer, format="PNG")
output_buffer.seek(0)
while output_buffer.tell() > max_size:
# Reduce the image size by resizing it to 90% of the original dimensions
image = image.resize((int(image.width * 0.9), int(image.height * 0.9)))
output_buffer = BytesIO()
image.save(output_buffer, format="PNG")
output_buffer.seek(0)
return image
# Main application function
def main():
st.title("Background Removal App")
st.markdown("Upload an image, and we'll remove the background for you using the Remove.bg API.")
# Hardcoded API Key
api_key = "your_api_key_here" # Replace this with your actual API key
# File uploader
uploaded_file = st.file_uploader("Upload an image (JPG, PNG)", type=["jpg", "jpeg", "png"])
if uploaded_file:
try:
# Load the uploaded image
image = Image.open(uploaded_file).convert("RGBA")
st.image(image, caption="Original Image", use_column_width=True)
# Check file size (in bytes)
image_size = uploaded_file.size
st.write(f"Uploaded image size: {image_size / (1024 * 1024):.2f} MB")
if image_size > 22 * 1024 * 1024:
st.warning("The image exceeds the 22MB limit. It will be resized to fit within the limit.")
# Resize image if it exceeds 22MB
image = resize_image(image)
st.write("Removing background...")
# Remove background
output_image = remove_background(image, api_key)
# Display result
st.image(output_image, caption="Background Removed", use_column_width=True)
# Save the result to a buffer
output_buffer = BytesIO()
output_image.save(output_buffer, format="PNG")
output_buffer.seek(0)
# Download button
st.download_button(
label="Download PNG Image",
data=output_buffer,
file_name="background_removed.png",
mime="image/png",
)
except Exception as e:
st.error(f"An error occurred: {e}")
st.markdown("""
**Instructions:**
1. Get your Remove.bg API key from [Remove.bg](https://www.remove.bg/api).
2. Upload an image in JPG or PNG format.
3. Download the processed image as a PNG file.
""")
if __name__ == "__main__":
main()