Alibrown's picture
Rename app.py to top.py
1ab18f9 verified
raw
history blame
3.86 kB
import streamlit as st
from PIL import Image
import io
import traceback
def compress_image(image, format='webp', quality=85):
try:
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format=format.upper(), quality=quality)
img_byte_arr.seek(0)
return Image.open(img_byte_arr)
except Exception as e:
st.error(f"Fehler bei Bildkompression: {e}")
st.error(traceback.format_exc())
return None
def main():
st.title("Bild Optimierungs-Tool")
st.sidebar.header("Optimierungseinstellungen")
uploaded_file = st.file_uploader("Wählen Sie ein Bild", type=['jpg', 'png', 'jpeg', 'webp'])
if uploaded_file is not None:
try:
original_image = Image.open(uploaded_file)
st.subheader("Originalbild")
st.image(original_image, caption="Ursprüngliches Bild")
# Ursprungsgröße anzeigen
original_size_bytes = len(uploaded_file.getvalue())
st.write(f"Ursprüngliche Bildgröße: {original_size_bytes} Bytes")
compression_quality = st.sidebar.slider(
"Kompressionsqualität",
min_value=1,
max_value=100,
value=85
)
# Nur ein Format wählbar
target_format = st.sidebar.selectbox(
"Zielformat",
['webp', 'jpg', 'png']
)
if st.button("Bild optimieren"):
try:
# Bild optimieren
optimized_image = compress_image(
original_image,
format=target_format,
quality=compression_quality
)
if optimized_image:
# Speichern im Speicher
img_byte_arr = io.BytesIO()
optimized_image.save(img_byte_arr, format=target_format.upper(), quality=compression_quality)
img_byte_arr.seek(0)
# Größenvergleich
optimized_size_bytes = img_byte_arr.getbuffer().nbytes
compression_ratio = (1 - optimized_size_bytes / original_size_bytes) * 100
st.subheader("Optimierungsergebnisse")
col1, col2 = st.columns(2)
with col1:
st.image(optimized_image, caption=f"Optimiert ({target_format.upper()})")
with col2:
st.write(f"Ursprüngliche Größe: {original_size_bytes} Bytes")
st.write(f"Optimierte Größe: {optimized_size_bytes} Bytes")
st.write(f"Kompressionsrate: {compression_ratio:.2f}%")
# Download-Button
st.download_button(
label=f"Download {target_format.upper()}",
data=img_byte_arr,
file_name=f"optimized_image.{target_format}",
mime=f"image/{target_format}"
)
else:
st.error("Bildoptimierung fehlgeschlagen")
except Exception as e:
st.error(f"Fehler bei Bildoptimierung: {e}")
st.error(traceback.format_exc())
except Exception as e:
st.error(f"Fehler beim Laden des Bildes: {e}")
st.error(traceback.format_exc())
if __name__ == "__main__":
main()