sharma-kanishka commited on
Commit
6ac8cc3
·
verified ·
1 Parent(s): 74b0513

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +35 -41
utils.py CHANGED
@@ -1,41 +1,35 @@
1
- import base64
2
- import os
3
-
4
- def encode_image_to_base64(image_path):
5
- """
6
- Read an image file and convert it to a base64 string.
7
-
8
- Args:
9
- image_path (str): Path to the image file
10
-
11
- Returns:
12
- tuple: (base64_string, mime_type)
13
- """
14
- try:
15
- # Get the file extension
16
- _, ext = os.path.splitext(image_path)
17
- ext = ext.lower()
18
-
19
- # Determine MIME type
20
- mime_types = {
21
- '.png': 'image/png',
22
- '.jpg': 'image/jpeg',
23
- '.jpeg': 'image/jpeg'
24
- }
25
-
26
- mime_type = mime_types.get(ext, 'image/png')
27
-
28
- with open(image_path, 'rb') as image_file:
29
- # Read the binary data
30
- binary_data = image_file.read()
31
- # Encode to base64
32
- base64_encoded = base64.b64encode(binary_data)
33
- # Convert to string and remove b'' prefix
34
- return base64_encoded.decode('utf-8'), mime_type
35
- except FileNotFoundError:
36
- raise FileNotFoundError(f"Image file not found at: {image_path}")
37
- except Exception as e:
38
- raise Exception(f"Error encoding image: {str(e)}")
39
-
40
-
41
- # print(encode_image_to_base64("backiee-81547.jpg"))
 
1
+ import base64
2
+
3
+ def encode_image_to_base64(uploaded_file):
4
+ """
5
+ Convert a Streamlit uploaded file to a base64 string.
6
+
7
+ Args:
8
+ uploaded_file (UploadedFile): File object from st.file_uploader()
9
+
10
+ Returns:
11
+ tuple: (base64_string, mime_type)
12
+ """
13
+ try:
14
+ # Get the file extension
15
+ file_type = uploaded_file.type
16
+
17
+ # Determine MIME type
18
+ mime_types = {
19
+ 'image/png': 'image/png',
20
+ 'image/jpeg': 'image/jpeg'
21
+ }
22
+
23
+ mime_type = mime_types.get(file_type, 'image/png')
24
+
25
+ # Read the binary data directly from the uploaded file
26
+ binary_data = uploaded_file.getvalue()
27
+
28
+ # Encode to base64
29
+ base64_encoded = base64.b64encode(binary_data)
30
+
31
+ # Convert to string and remove b'' prefix
32
+ return base64_encoded.decode('utf-8'), mime_type
33
+
34
+ except Exception as e:
35
+ raise Exception(f"Error encoding image: {str(e)}")