File size: 2,455 Bytes
7a0d1e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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