Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from PIL import Image | |
| import io | |
| def resize_image(image, target_size_kb=None, quality=85): | |
| """Resizes and compresses an image.""" | |
| img = Image.open(image) | |
| img_byte_arr = io.BytesIO() | |
| img.save(img_byte_arr, format='JPEG', quality=quality) | |
| current_size_kb = len(img_byte_arr.getvalue()) / 1024 | |
| # Resize based on target size (if provided) | |
| if target_size_kb: | |
| while current_size_kb > target_size_kb and quality > 10: | |
| quality -= 5 | |
| img_byte_arr = io.BytesIO() | |
| img.save(img_byte_arr, format='JPEG', quality=quality) | |
| current_size_kb = len(img_byte_arr.getvalue()) / 1024 | |
| else: | |
| # Resize based on quality | |
| pass # No resizing for quality-based option | |
| img = Image.open(img_byte_arr) | |
| return img | |
| st.title("Image Resizer") | |
| st.write("Resize and compress your images!") | |
| # Upload image | |
| uploaded_file = st.file_uploader("Choose an Image:", type=["jpg", "jpeg", "png"]) | |
| if uploaded_file is not None: | |
| # Option selection for resizing | |
| resize_option = st.selectbox("Resize Option:", ("Percentage Quality", "Desired Output Size")) | |
| if resize_option == "Percentage Quality": | |
| # User input for quality | |
| quality = st.slider("Quality (%)", min_value=10, max_value=100, value=85) | |
| elif resize_option == "Desired Output Size": | |
| # Options for size units | |
| size_unit_options = ("KB", "MB") | |
| size_unit = st.selectbox("Size Unit", size_unit_options) | |
| # User input for size | |
| target_size = st.number_input("Target Size", min_value=1) | |
| # Convert target size to KB based on unit | |
| if size_unit == "MB": | |
| target_size_kb = target_size * 1024 | |
| else: | |
| target_size_kb = target_size | |
| # Process and display image | |
| if uploaded_file and (quality or target_size_kb): | |
| resized_image = resize_image(uploaded_file, target_size_kb, quality) | |
| st.image(resized_image, caption="Resized Image") | |
| # Download link | |
| with io.BytesIO() as buffer: | |
| resized_image.save(buffer, format="JPEG") | |
| download_link = st.download_button( | |
| label="Download Resized Image", | |
| data=buffer.getvalue(), | |
| file_name="resized_image.jpg", | |
| mime="image/jpeg", | |
| ) | |
| # Requirements (req.txt) | |
| # Since the app uses only built-in libraries (streamlit and Pillow), there's no need for an external requirements file. | |
| # However, if you plan to use additional libraries, you can create a req.txt file listing them. | |
| # For example: | |
| # streamlit | |
| # Pillow |