2013-07-03 187 views
-5

我想自動將帶有png圖像的html文件轉換爲內嵌在單個html文件中的base64圖像。有沒有這樣的即用型工具?將html圖像轉換爲內聯base64

+0

Java程序員可以使用[這](http://stackoverflow.com/questions/9388264/jeditorpane -with-inline-image)來製作一個工具。 –

回答

2

這是我最近使用簡單的Python腳本...它作爲一個過濾器:

#!/usr/bin/env python 
# -*- coding:utf-8 -*- 

import fileinput 
import re 
import base64 
import mimetypes 
import os 


def replacement(match): 

    fn = match.groups()[0] 

    if os.path.isfile(fn): 
     return 'src="data:%s;base64,%s"' % (mimetypes.guess_type(fn)[0], base64.b64encode(open(fn, 'rb').read())) 

    return match.group() 



def main(): 

    fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf8")) 

    while True: 
     line = fi.readline() 
     if not line: 
      break 
     print re.sub(r'src="(.*?)"', replacement, line).encode('utf-8'), 



if __name__ == '__main__': 
    main()