JPEG Base64 Image String (Python)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is offline Offline Oct 6th, 2005, 4:54 pm |
0
This short code lets you create a base64 encoded image string, that you can copy and paste into your Python program code to display relatively small embedded images.

For a typical application see:
http://www.daniweb.com/code/snippet393.html
Quick reply to this message  
Python Syntax
  1. # base64 encoding converts binary data to plain text
  2. # it stores each group of three binary bytes as a group of four characters from the text set:
  3. # ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789+/
  4. # the = character is used for padding at the end of the data stream
  5. # this way an image file can be represented as a string to transmit or
  6. # a short image can be embedded in code as a string, you can insert newlines at
  7. # convenient locations into this embedded string, they will be ignored when
  8. # decoding with for instance jpg1 = base64.b64decode(jpg1_b64)
  9. # tested with Python24 vegaseat 06oct2005
  10.  
  11. import base64
  12.  
  13. # pick a jpeg file you have and want ...
  14. jpgfile = "halloween3.jpg"
  15.  
  16. # note: binary read "rb" is required!
  17. # this gives a one line string ...
  18. #jpg_text = 'jpg1_b64 = \\\n"""' + base64.b64encode(open(jpgfile,"rb").read()) + '"""'
  19. # another option, inserts newlines about every 76 characters, easier to copy and paste!
  20. jpg_text = 'jpg1_b64 = \\\n"""' + base64.encodestring(open(jpgfile,"rb").read()) + '"""'
  21.  
  22. print jpg_text
  23.  
  24. # optionally save to a text file
  25. filename = "jpg1_b64.txt"
  26. try:
  27. fout = open(filename, "w")
  28. fout.write(jpg_text)
  29. fout.close()
  30. except IOError:
  31. print "File %s could not be saved!" % filename

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC