negative / app.py
habib926653's picture
Update app.py
57ad318 verified
import streamlit as st
import requests
import base64
from PIL import Image, ImageOps, ImageDraw
from io import BytesIO
import re
def process_image(image_data, is_base64=False):
try:
if is_base64:
# Remove potential base64 headers (like 'data:image/png;base64,')
image_data = re.sub(r"^data:image/\w+;base64,", "", image_data)
image_data = base64.b64decode(image_data)
image = Image.open(BytesIO(image_data)).convert("RGB")
# Convert to negative
negative = ImageOps.invert(image)
# Draw a red circular dot in the center
draw = ImageDraw.Draw(negative)
width, height = negative.size
dot_radius = max(width, height) // 50 # Dynamic dot size
center_x, center_y = width // 2, height // 2
draw.ellipse(
(center_x - dot_radius, center_y - dot_radius, center_x + dot_radius, center_y + dot_radius),
fill=(255, 0, 0)
)
return negative
except Exception as e:
st.error(f"Error processing image: {e}")
return None
def main():
st.title("Negative Effect for Image")
input_method = st.radio("Select Image Input Method:", ("Direct Image URL", "Base64 Image"))
img = None # Ensure img is always defined
if input_method == "Direct Image URL":
image_url = st.text_input("Enter Image URL:")
if image_url:
try:
response = requests.get(image_url, stream=True)
response.raise_for_status()
img = process_image(response.content)
except Exception as e:
st.error(f"Error fetching image: {e}")
elif input_method == "Base64 Image":
base64_image = st.text_area("Enter Base64 Encoded Image:")
if base64_image.strip():
try:
img = process_image(base64_image, is_base64=True)
except Exception as e:
st.error(f"Error processing base64 image: {e}")
if img is not None:
st.image(img, caption="Processed Image", use_column_width=True)
else:
st.warning("Please provide a valid image input.")
if __name__ == "__main__":
main()