Skip to content

Instantly share code, notes, and snippets.

@GeorgeNava
Created May 8, 2010 14:32

Revisions

  1. GeorgeNava renamed this gist May 8, 2010. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. GeorgeNava created this gist May 8, 2010.
    37 changes: 37 additions & 0 deletions ImageToBase64
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    '''
    This program converts all images in a folder to base64
    for embedding in an html page inside a <style> tag like:
    <style>
    .img_name1{content:url("data:image/jpg;base64,abcdef...");}
    .img_name2{content:url("data:image/jpg;base64,abcdef...");}
    </style>
    The 'content' property only works in webkit browsers.
    '''

    import os,glob,base64

    path = './img/'
    name = 'base64.css'

    def save64(path,ext):
    files = glob.glob(os.path.join(path,'*.%s'%ext))
    for img in files:
    print img
    fh = open(img,"rb")
    fc = fh.read()
    fh.close()
    fb = base64.b64encode(fc)
    fn = os.path.splitext(os.path.basename(img))[0]
    out.write('.img_')
    out.write(fn)
    out.write('{content:url("data:image/%s;base64,'%ext)
    out.write(fb)
    out.write('");}\n')

    out = open(os.path.join(path,name),'w')
    out.write('<style>\n')
    save64(path,'jpg')
    save64(path,'png')
    save64(path,'gif')
    out.write('</style>\n')
    out.close()