前端為了減少 request 數量可以說是用盡各種方式, Javascript 壓成一支, css 壓成一支,圖片用 image sprite 壓成一張大圖,用盡各種方式把 request 數量減少,讓使用者體驗變得更好。
對於圖片來說 image sprite 是一種很好的方法,但是總會問一下自已「能不能更好?」於是找到了 Data uri 的方式,把圖片轉換為字串,跟著 html, css 一起載入, HTML 的img tag 的 src ,或者 CSS 的 backbround-image 一並載入。產生 Data uri 有些線上工具可以使用,但基於懶人精神 懶得按滑鼠、懶得選取檔案、懶得連上網路(那你做 web 幹嘛!?) 所以就寫了一個簡單的工具,目的當然很簡單,不用上網( local 可以解決),不用使用滑鼠( command line 就可以執行),產生完自動幫我複製到剪貼簿(立馬可使用 ctrl + v)
根據 Caniuse 表示 Data uri 在 IE8+, firefox 2.0+, chrome 4.0+, safari 3.1+, opera 9.0+, 以及所有的 mobile browser 都有支援,所以網站如果是支援 IE8 以上的網頁應該是可以安心服用。
Gist - https://gist.github.com/IskenHuang/6434813
使用方法很簡單在下載後的檔案同目錄下輸入
node img YOUR_IMAGE_PATH
馬上就產出 data uri 並且複製到剪貼簿中,立馬享有 ctrl + v 快速產出的快感( Mac only ),產生出來的字串包含了 data:image/png;base64, 所以直接貼入 HTML img 的 src="PASTE_HERE" ,或 CSS background-image 的 url( PASTE_HERE ) 中。
source
This file contains 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 is simple transfer image to data uri(base64 encode) nodejs command line tool | |
* | |
* require | |
* install nodejs v0.8+ | |
* | |
* how to use | |
* node img YOUR_IMAGE_FILE_PATH | |
* | |
* sample | |
* node img logo.png | |
* | |
*/ | |
var param = process.argv[2], | |
sp = param.split(/\./ig), | |
fs = require('fs'); | |
console.log('File name: ', param, sp[sp.length-1]); | |
console.log('============================== BEGIN ================================='); | |
fs.readFile( param , function(err, data) { | |
var base64data = new Buffer(data).toString('base64'), | |
imgString = 'data:image/' + sp[sp.length-1] + ';base64,' + base64data; | |
// copy to clipboard | |
pbcopy(imgString); | |
console.log(imgString); | |
console.log('============================== END ================================='); | |
}); | |
/** | |
* copy string to clipboard | |
* mac only | |
* | |
* @param {String} data put string to clipboard | |
* @return {String} return original param | |
*/ | |
function pbcopy(data) { | |
var proc = require('child_process').spawn('pbcopy'); | |
proc.stdin.write(data); | |
proc.stdin.end(); | |
return data; | |
} |
相關連結
Caniuse - datauri
Gist - https://gist.github.com/IskenHuang/6434813
沒有留言:
張貼留言