Spaces:
Build error
Build error
File size: 999 Bytes
6ac8cc3 |
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 |
import base64
def encode_image_to_base64(uploaded_file):
"""
Convert a Streamlit uploaded file to a base64 string.
Args:
uploaded_file (UploadedFile): File object from st.file_uploader()
Returns:
tuple: (base64_string, mime_type)
"""
try:
# Get the file extension
file_type = uploaded_file.type
# Determine MIME type
mime_types = {
'image/png': 'image/png',
'image/jpeg': 'image/jpeg'
}
mime_type = mime_types.get(file_type, 'image/png')
# Read the binary data directly from the uploaded file
binary_data = uploaded_file.getvalue()
# Encode to base64
base64_encoded = base64.b64encode(binary_data)
# Convert to string and remove b'' prefix
return base64_encoded.decode('utf-8'), mime_type
except Exception as e:
raise Exception(f"Error encoding image: {str(e)}") |