furas

Python - convert image from .zip file to base64 string in html (Stackoverflow)

Oct 2nd, 2025 (edited)
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. # date: 2025.10.02
  2.  
  3. # [Staging Ground: Display images from zip file in HTML table without extracting them - Stack Overflow](https://stackoverflow.com/staging-ground/79781002#comment140773792_79781002)
  4.  
  5. # - example image from Wikipedia [Lenna](https://en.wikipedia.org/wiki/Lenna) -
  6. # wget https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png -O lenna.png
  7.  
  8. # - create zip file -
  9. # zip data.zip lenna.png
  10.  
  11. # - run www server with index.html -
  12. # python3 -m http.server
  13.  
  14. # tested on Linux Mint, Python 3.13
  15.  
  16. import zipfile
  17. import base64
  18.  
  19. filename_zip = "data.zip"
  20. filename_image = "lenna.png"
  21. filename_html = "index.html"
  22.  
  23. with zipfile.ZipFile(filename_zip) as zip_file:
  24.     with zip_file.open(filename_image) as image_file:
  25.         image_bytes = image_file.read()
  26.         base64_bytes = base64.b64encode(image_bytes)
  27.         base64_string = base64_bytes.decode("utf-8")
  28.         html = f'<img src="data:image/png;base64, {base64_string}">'
  29.  
  30.         with open(filename_html, "w") as html_file:
  31.             html_file.write(html)
Add Comment
Please, Sign In to add comment