mbtokb / app.py
razaAhmed's picture
Upload 2 files
8bcdfb3
import streamlit as st
from PIL import Image
import io
import base64
def mb_to_kb_converter(image_path, output_path, target_size_kb):
try:
# Open the image file
with Image.open(image_path) as img:
# Calculate the target size in bytes
target_size_bytes = target_size_kb * 1024
# Resize the image while maintaining the aspect ratio
img.thumbnail((300, 300))
# Save the image with reduced quality to decrease file size
img.save(output_path, format="JPEG", quality=85)
# Ensure the image meets the target size constraint
while io.BytesIO().getbuffer().nbytes > target_size_bytes:
img.thumbnail((img.width // 2, img.height // 2))
img.save(output_path, format="JPEG", quality=85)
except Exception as e:
st.error(f"Error: {e}")
return None
return output_path
def main():
st.title("Image MB to KB Converter")
uploaded_file = st.file_uploader("Choose an image file (JPG or PNG)", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
st.write("")
# Set the target size in KB
target_size_kb = 100 # You can adjust this value
# Convert MB to KB and get the result as a BytesIO buffer
output_path = "converted_image.jpg"
converted_path = mb_to_kb_converter(uploaded_file, output_path, target_size_kb)
if converted_path is not None:
st.success("Conversion complete!")
# Encode the content of the buffer to base64 and then decode to UTF-8
with open(converted_path, "rb") as image_file:
b64_encoded = base64.b64encode(image_file.read()).decode("utf-8")
# Display the converted image
st.image(converted_path, caption="Converted Image", use_column_width=True)
# Display the download link for the converted image
st.markdown(
f'<a href="data:image/jpeg;base64,{b64_encoded}" download="converted_image.jpg">Download Converted Image</a>',
unsafe_allow_html=True
)
else:
st.error("Conversion failed. Please try again.")
if __name__ == "__main__":
main()