rishi9440 commited on
Commit
164ffb9
1 Parent(s): 79690b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -5
app.py CHANGED
@@ -12,6 +12,35 @@ apply_prod_style(st) # NOTE: Uncomment this for production!
12
  def V_SPACE(lines):
13
  for _ in range(lines):
14
  st.write(' ')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  uploaded_file = st.file_uploader(
17
  label="Upload your photo here",
@@ -42,9 +71,8 @@ if uploaded_file is not None:
42
  with st.expander("Success!", expanded=True):
43
  st.image(img_output)
44
  uploaded_name = os.path.splitext(uploaded_file.name)[0]
45
- st.download_button(
46
- label="Save Image",
47
- data=img_output,
48
- file_name=f'{uploaded_name}.png',
49
- mime="image/png"
50
  )
 
12
  def V_SPACE(lines):
13
  for _ in range(lines):
14
  st.write(' ')
15
+
16
+ def image_download_button(pil_image, filename: str, fmt: str, label="Download"):
17
+ if fmt not in ["jpg", "png"]:
18
+ raise Exception(f"Unknown image format (Available: {fmt} - case sensitive)")
19
+
20
+ pil_format = "JPEG" if fmt == "jpg" else "PNG"
21
+ file_format = "jpg" if fmt == "jpg" else "png"
22
+ mime = "image/jpeg/?target=external" if fmt == "jpg" else "image/png/?target=external"
23
+
24
+ buf = BytesIO()
25
+ pil_image.save(buf, format=pil_format)
26
+
27
+ # Return the binary data as a string
28
+ return buf.getvalue()
29
+
30
+ def download_button(pil_image, filename: str, fmt: str, label="Download"):
31
+ if fmt not in ["jpg", "png"]:
32
+ raise Exception(f"Unknown image format (Available: {fmt} - case sensitive)")
33
+
34
+ pil_format = "JPEG" if fmt == "jpg" else "PNG"
35
+ file_format = "jpg" if fmt == "jpg" else "png"
36
+ mime = "image/jpeg/?target=external" if fmt == "jpg" else "image/png/?target=external"
37
+
38
+ buf = BytesIO()
39
+ pil_image.save(buf, format=pil_format)
40
+
41
+ # Display the download button
42
+ href = f'<a href="data:{mime};base64,{buf.getvalue().decode("utf-8")}" download="{filename}.{file_format}">{label}</a>'
43
+ st.markdown(href, unsafe_allow_html=True)
44
 
45
  uploaded_file = st.file_uploader(
46
  label="Upload your photo here",
 
71
  with st.expander("Success!", expanded=True):
72
  st.image(img_output)
73
  uploaded_name = os.path.splitext(uploaded_file.name)[0]
74
+ download_button(
75
+ pil_image=img_output,
76
+ filename=uploaded_name,
77
+ fmt="png"
 
78
  )