Skip to content

Commit

Permalink
Merge pull request #117 from Himanshi-m/main
Browse files Browse the repository at this point in the history
Addition of Image tool to Automation Tools
  • Loading branch information
UTSAVS26 authored Oct 5, 2024
2 parents c7bdf39 + ef935b7 commit 3673b69
Show file tree
Hide file tree
Showing 3 changed files with 355 additions and 0 deletions.
264 changes: 264 additions & 0 deletions Automation_Tools/Image-Tool/Image_Tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
import streamlit as st
from PIL import Image, ImageEnhance
from io import BytesIO
from streamlit_cropper import st_cropper

# Initialize session state for navigation
if 'page' not in st.session_state:
st.session_state.page = "Home"

# Function to navigate to a different page
def navigate_to(page):
st.session_state.page = page

# Set up the main window
st.title("Image Manipulation Tool")

# Menu bar
menu = st.sidebar.selectbox("Menu", ["Home", "Resize Image", "Convert Image", "Crop Image", "Enhance Image", "Help"], index=["Home", "Resize Image", "Convert Image", "Crop Image", "Enhance Image", "Help"].index(st.session_state.page))

# Home Page
if menu == "Home":
st.header("Welcome to the Image Manipulation Tool!")
st.write("""
This tool allows you to perform various image manipulation tasks including resizing, converting, cropping, and enhancing images.
Use the navigation menu on the left to access different functionalities.
""")

# Create a grid for navigation
col1, col2, col3 = st.columns(3)

with col1:
st.subheader("Resize Image")
st.write("Resize your images by specifying dimensions or percentage.")
if st.button("Go to Resize Image"):
navigate_to("Resize Image")

with col2:
st.subheader("Convert Image")
st.write("Convert your images to different formats.")
if st.button("Go to Convert Image"):
navigate_to("Convert Image")

with col3:
st.subheader("Crop Image")
st.write("Crop your images to custom dimensions.")
if st.button("Go to Crop Image"):
navigate_to("Crop Image")

col4, col5, col6 = st.columns(3)

with col4:
st.subheader("Enhance Image")
st.write("Adjust brightness, contrast, and saturation of your images.")
if st.button("Go to Enhance Image"):
navigate_to("Enhance Image")

with col5:
st.subheader("Help")
st.write("Get help and information about how to use this tool.")
if st.button("Go to Help"):
navigate_to("Help")

# Resize Image Page
elif menu == "Resize Image":
st.header("Resize Image")

# File uploader
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"], help="Upload an image file to resize.")

if uploaded_file is not None:
image = Image.open(uploaded_file)

# Resize options
resize_option = st.radio("Resize Option", ("By Dimensions", "By Percentage"), help="Choose how you want to resize the image.")

if resize_option == "By Dimensions":
width = st.number_input("Width", value=image.width, help="Enter the new width for the image.")
height = st.number_input("Height", value=image.height, help="Enter the new height for the image.")
else:
percentage = st.number_input("Percentage", value=100, help="Enter the percentage to scale the image.")
width = int(image.width * (percentage / 100))
height = int(image.height * (percentage / 100))

if st.button("Resize", help="Click to resize the image."):
progress = st.progress(0)
resized_image = image.resize((width, height))
progress.progress(50)

# Estimate file size
buffer = BytesIO()
resized_image.save(buffer, format="PNG")
estimated_size = len(buffer.getvalue()) / 1024 # in KB
st.write(f"Estimated file size: {estimated_size:.2f} KB")

# Display images side by side
col1, col2 = st.columns(2)
with col1:
st.image(image, caption='Uploaded Image', use_column_width=True)
with col2:
st.image(resized_image, caption='Resized Image', use_column_width=True)

# Provide a download button
buffer.seek(0)
st.download_button(
label="Download Resized Image",
data=buffer,
file_name="resized_image.png",
mime="image/png",
help="Click to download the resized image."
)
st.success("Image ready for download")
progress.progress(100)

# Convert Image Page
elif menu == "Convert Image":
st.header("Convert Image")

# File uploader
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp", "ico"], help="Upload an image file to convert.")

if uploaded_file is not None:
image = Image.open(uploaded_file)

# Format selection
format_option = st.selectbox("Select Output Format", ["JPEG", "PNG", "BMP", "GIF", "TIFF", "WEBP", "ICO"], help="Choose the output format for the image.")

# Quality adjustment for all formats
quality = st.slider("Quality", 1, 100, 100, help="Adjust the quality of the output image.")

if st.button("Convert", help="Click to convert the image."):
progress = st.progress(0)
buffer = BytesIO()
image.save(buffer, format=format_option, quality=quality)
buffer.seek(0)
progress.progress(50)

# Estimate file size
estimated_size = len(buffer.getvalue()) / 1024 # in KB
st.write(f"Estimated file size: {estimated_size:.2f} KB")

# Display images side by side
col1, col2 = st.columns(2)
with col1:
st.image(image, caption='Uploaded Image', use_column_width=True)
with col2:
st.image(buffer, caption=f'Converted Image ({format_option})', use_column_width=True)

# Provide a download button
st.download_button(
label="Download Converted Image",
data=buffer,
file_name=f"converted_image.{format_option.lower()}",
mime=f"image/{format_option.lower()}",
help="Click to download the converted image."
)
st.success("Image ready for download")
progress.progress(100)

# Crop Image Page
elif menu == "Crop Image":
st.header("Crop Image")

# File uploader
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"], help="Upload an image file to crop.")

if uploaded_file is not None:
image = Image.open(uploaded_file)

# Aspect ratio options
aspect_ratio = st.selectbox("Aspect Ratio", ["Freeform", "1:1", "4:3", "16:9"], help="Choose the aspect ratio for cropping.")
aspect_dict = {"Freeform": None, "1:1": (1, 1), "4:3": (4, 3), "16:9": (16, 9)}

# Crop the image
progress = st.progress(0)
cropped_image = st_cropper(image, aspect_ratio=aspect_dict[aspect_ratio], box_color='blue', return_type='image')
progress.progress(50)

# Display images side by side
col1, col2 = st.columns(2)
with col1:
st.image(image, caption='Uploaded Image', use_column_width=True)
with col2:
st.image(cropped_image, caption='Cropped Image', use_column_width=True)

# Provide a download button
buffer = BytesIO()
cropped_image.save(buffer, format="PNG")
buffer.seek(0)
st.download_button(
label="Download Cropped Image",
data=buffer,
file_name="cropped_image.png",
mime="image/png",
help="Click to download the cropped image."
)
st.success("Image ready for download")
progress.progress(100)

# Enhance Image Page
elif menu == "Enhance Image":
st.header("Enhance Image")

# File uploader
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"], help="Upload an image file to enhance.")

if uploaded_file is not None:
image = Image.open(uploaded_file)

# Enhancement options
brightness = st.slider("Brightness", 0.1, 2.0, 1.0, help="Adjust the brightness of the image.")
contrast = st.slider("Contrast", 0.1, 2.0, 1.0, help="Adjust the contrast of the image.")
saturation = st.slider("Saturation", 0.1, 2.0, 1.0, help="Adjust the saturation of the image.")

progress = st.progress(0)
enhancer = ImageEnhance.Brightness(image)
enhanced_image = enhancer.enhance(brightness)
progress.progress(25)
enhancer = ImageEnhance.Contrast(enhanced_image)
enhanced_image = enhancer.enhance(contrast)
progress.progress(50)
enhancer = ImageEnhance.Color(enhanced_image)
enhanced_image = enhancer.enhance(saturation)
progress.progress(75)

# Display images side by side
col1, col2 = st.columns(2)
with col1:
st.image(image, caption='Uploaded Image', use_column_width=True)
with col2:
st.image(enhanced_image, caption='Enhanced Image', use_column_width=True)

# Provide a download button
buffer = BytesIO()
enhanced_image.save(buffer, format="PNG")
buffer.seek(0)
st.download_button(
label="Download Enhanced Image",
data=buffer,
file_name="enhanced_image.png",
mime="image/png",
help="Click to download the enhanced image."
)
st.success("Image ready for download")
progress.progress(100)

# Help Page
elif menu == "Help":
st.header("Help")
st.write("""
**Image Manipulation Tool** allows you to perform various image manipulation tasks including resizing, converting, cropping, and enhancing images.
**Features:**
- **Resize Image:** Resize your images by specifying dimensions or percentage.
- **Convert Image:** Convert your images to different formats.
- **Crop Image:** Crop your images to custom dimensions.
- **Enhance Image:** Adjust brightness, contrast, and saturation of your images.
**Made by [@Himanshi-M](https://github.com/Himanshi-M)**
""")

# Run the app
if __name__ == "__main__":
pass # No need to call any Streamlit method here
88 changes: 88 additions & 0 deletions Automation_Tools/Image-Tool/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Image Manipulation Tool

## AIM
To provide an intuitive Python-based image editing tool using **Streamlit**, allowing users to resize, crop, convert, and enhance images with real-time previews.

## DATASET LINK
No dataset is required for this project, as it processes user-uploaded images.

## MY NOTEBOOK LINK
No notebook was used in this project.

## DESCRIPTION
This project aims to create a simple yet powerful tool for manipulating images. Image manipulation is necessary for a variety of use cases such as preparing images for websites, social media, or applications where specific formats or dimensions are required. It can save users time by offering an all-in-one interface to perform basic editing tasks without needing advanced software.

**Approach:**
- The project started with research into image manipulation using Python libraries like `Pillow` and `Streamlit`.
- Tools like `streamlit-cropper` were integrated for easier cropping.

**Additional Resources:**
- Streamlit documentation https://streamlit.io/
- Pillow library documentation https://readthedocs.org/projects/pillow/

## EXPLANATION

### DETAILS OF THE DIFFERENT FEATURES
1. **Image Resizing**: Users can resize images by height, width, or percentage.
2. **Image Cropping**: Provides an interactive cropping tool using `streamlit-cropper` with aspect ratio control.
3. **Format Conversion**: Converts images to popular formats like JPEG, PNG, BMP, and GIF.
4. **Enhancement**: Adjust brightness, contrast, sharpness, and color.

### WHAT I HAVE DONE
1. Researched tools like `Streamlit` and `Pillow` for image manipulation.
2. Developed a basic interface using `Streamlit` for uploading and previewing images.
3. Integrated resizing functionality with live previews.
4. Added image cropping using `streamlit-cropper`.
5. Implemented format conversion with compression quality controls.
6. Enabled image enhancement options (brightness, contrast, sharpness, color).
7. Ensured images can be saved and downloaded after edits.

### PROJECT TRADE-OFFS AND SOLUTIONS
1. **Trade-off 1**: Keeping the interface simple vs. adding advanced features.
- **Solution**: Prioritized simplicity, only adding essential features like resizing, cropping, and enhancement.
2. **Trade-off 2**: Balancing performance with real-time previews.
- **Solution**: Implemented lightweight image previews using `Pillow` and optimized backend logic.

### LIBRARIES NEEDED
- `streamlit`
- `Pillow`
- `streamlit-cropper`

### SCREENSHOTS
![image](https://github.com/user-attachments/assets/3900c172-722d-417a-ab00-b99d9cb32569)
![Screenshot_5-10-2024_172211_localhost](https://github.com/user-attachments/assets/bbafb96d-8418-4455-985c-c8fbcc371896)
![image](https://github.com/user-attachments/assets/6d06c6f7-06b0-4804-a686-f703ac85600f)
![image](https://github.com/user-attachments/assets/92d18dad-f108-420e-93f2-cfebd30fb171)
![image](https://github.com/user-attachments/assets/04589bab-1172-4333-b21d-5f588138bbad)
![image](https://github.com/user-attachments/assets/d4f2f013-9886-4e3f-a77b-8f25b458b3cb)


### MODELS USED AND THEIR ACCURACIES
No machine learning models are used in this project.

## CONCLUSION

### WHAT YOU HAVE LEARNED
- Practical application of Python in image processing.
- Using `Streamlit` to create web-based applications.
- Using `Pillow`'s `Image` to modify and handle images.
- Importance of balancing simplicity with functionality in a user interface.

### USE CASES OF THIS MODEL
1. **Content Creators**: Resize and enhance images for social media or blogs.
2. **Web Developers**: Optimize image sizes for website performance.

### HOW TO INTEGRATE THIS TOOL IN REAL WORLD
1. Deploy the tool on a cloud service.
2. Embed it as a standalone web app.
3. Use the tool for real-time image processing needs for websites or applications.

### YOUR NAME
*Himanshi Maheshwari*

[![LinkedIn](https://img.shields.io/badge/linkedin-%230077B5.svg?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/himanshimaheshwari)
[![GitHub](https://img.shields.io/badge/github-%2312100E.svg?style=for-the-badge&logo=github&logoColor=white)](https://github.com/Himanshi-M)
[![Discord](https://img.shields.io/badge/discord-%237289DA.svg?style=for-the-badge&logo=discord&logoColor=white)](https://discord.com/users/himanshi-maheshwari)

#### Happy Coding 🧑‍💻
### Show some  ❤️  by  🌟  this repository!
3 changes: 3 additions & 0 deletions Automation_Tools/Image-Tool/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
streamlit
Pillow
streamlit-cropper

0 comments on commit 3673b69

Please sign in to comment.