|
import streamlit as st |
|
from PIL import Image, ImageFile, UnidentifiedImageError |
|
from io import BytesIO |
|
|
|
ImageFile.LOAD_TRUNCATED_IMAGES = True |
|
|
|
st.title("Reductor de tamaño de imágenes a PNG") |
|
|
|
|
|
uploaded_files = st.file_uploader("Elige las imágenes", type=["png", "jpg", "jpeg", "webp", "tiff", "bmp"], accept_multiple_files=True) |
|
|
|
MAX_SIZE = 1 * 1024 * 1024 |
|
|
|
def compress_image(image, initial_compression=1, step=1): |
|
compression = initial_compression |
|
output_data = None |
|
with BytesIO() as output: |
|
while compression <= 9: |
|
output.seek(0) |
|
image.save(output, format="PNG", compress_level=compression) |
|
if len(output.getvalue()) <= MAX_SIZE: |
|
output_data = output.getvalue() |
|
break |
|
compression += step |
|
|
|
if output_data is None: |
|
with BytesIO() as output: |
|
image.save(output, format="PNG", compress_level=9) |
|
output_data = output.getvalue() |
|
|
|
compressed_image = Image.open(BytesIO(output_data)) |
|
return compressed_image, output_data |
|
|
|
if uploaded_files: |
|
for uploaded_file in uploaded_files: |
|
image = Image.open(uploaded_file) |
|
|
|
|
|
compressed_image, compressed_data = compress_image(image) |
|
|
|
|
|
st.download_button( |
|
label="Descargar imagen comprimida", |
|
data=compressed_data, |
|
file_name=f"compressed_image.png", |
|
mime="image/png" |
|
) |
|
|
|
|
|
st.image(compressed_image, width=150) |
|
|