|
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: |
|
|
|
with Image.open(image_path) as img: |
|
|
|
target_size_bytes = target_size_kb * 1024 |
|
|
|
|
|
img.thumbnail((300, 300)) |
|
|
|
|
|
img.save(output_path, format="JPEG", quality=85) |
|
|
|
|
|
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("") |
|
|
|
|
|
target_size_kb = 100 |
|
|
|
|
|
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!") |
|
|
|
|
|
with open(converted_path, "rb") as image_file: |
|
b64_encoded = base64.b64encode(image_file.read()).decode("utf-8") |
|
|
|
|
|
|
|
|
|
st.image(converted_path, caption="Converted Image", use_column_width=True) |
|
|
|
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() |
|
|