Image_cropper / app.py
Saaquib's picture
Update app.py
2bc58c1
import streamlit as st
import os
import zipfile
from PIL import Image
def crop_image(image, left_mm, right_mm):
"""
Crop the image from both the left and right sides.
Args:
image (PIL.Image.Image): The input image.
left_mm (float): The amount to crop from the left side in millimeters.
right_mm (float): The amount to crop from the right side in millimeters.
Returns:
PIL.Image.Image: The cropped image.
"""
# Calculate the cropping width in pixels based on image DPI
dpi = image.info.get("dpi", 72)
width_mm = image.width * 25.4 / dpi
cropping_width = int((left_mm + right_mm) * image.width / width_mm)
# Calculate the left and right cropping boundaries
left_crop = int(left_mm * image.width / width_mm)
right_crop = image.width - int(right_mm * image.width / width_mm)
# Crop the image
cropped_image = image.crop((left_crop, 0, right_crop, image.height))
return cropped_image
def main():
st.title("Batch Image Cropper")
# Upload multiple image files
uploaded_files = st.file_uploader("Upload image files", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
if uploaded_files is not None:
col1, col2 = st.columns(2)
with col1:
left_mm = st.number_input("Crop from left (mm)", min_value=0.0, value=0.0, step=0.1)
with col2:
right_mm = st.number_input("Crop from right (mm)", min_value=0.0, value=0.0, step=0.1)
# Create a container to hold the cropped images
images_container = st.empty()
# Process each uploaded image file
cropped_images = []
for uploaded_file in uploaded_files:
# Open the image file
image = Image.open(uploaded_file)
# Crop the image
cropped_image = crop_image(image, left_mm, right_mm)
cropped_images.append(cropped_image)
# Display the original and cropped images side by side
col_width = 300
num_images = len(uploaded_files)
num_columns = 2
num_rows = (num_images + 1) // num_columns
for row in range(num_rows):
cols = st.columns(num_columns)
for col in range(num_columns):
index = row * num_columns + col
if index < num_images:
cols[col].subheader(f"Image {index+1}")
cols[col].image(uploaded_files[index], caption="Original Image", width=col_width)
cols[col].image(cropped_images[index], caption="Cropped Image", width=col_width)
# Save all cropped images
if st.button("Save All"):
zip_filename = "cropped_images.zip"
with zipfile.ZipFile(zip_filename, "w") as zipf:
for i, cropped_image in enumerate(cropped_images):
filename, ext = os.path.splitext(uploaded_files[i].name)
cropped_filename = f"cropped_{filename}.png"
cropped_image.save(cropped_filename)
zipf.write(cropped_filename)
os.remove(cropped_filename)
st.success(f"All cropped images saved successfully as {zip_filename}")
if __name__ == "__main__":
main()