Created
May 8, 2010 14:32
-
-
Save GeorgeNava/394588 to your computer and use it in GitHub Desktop.
Converts all images in a folder to base64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment