有時候我們需要往 HTML 裡插入一張圖片,卻苦於上線後找不到合適的空間存放這些圖片檔。有沒有可能把圖片直接「變成文字」,寫進 HTML 裡呢?答案是有的——透過 Base64 編碼,圖片就能以字串形式存在,不必再依賴外部檔案。(若不熟悉 Base64 的概念,建議先閱讀相關的編碼原理介紹,例如 Base64 線上工具與說明。)
現代瀏覽器提供的 FileReader 物件是關鍵,其中 readAsDataURL() 方法會把讀取的檔案轉成 data: 開頭的 Base64 字串。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS 圖片轉 Base64</title>
<script src="https://hovertree.com/ziyuan/jquery/jquery-2.2.0.min.js"></script>
<script>
function run(input_file, get_data) {
/* input_file:檔案選擇按鈕的物件 */
/* get_data:轉換成功後要呼叫的函式 */
if (typeof(FileReader) === 'undefined') {
alert("抱歉,你的瀏覽器不支援 FileReader,無法將圖片轉換為 Base64,請改用現代瀏覽器操作!");
} else {
try {
/* 圖片轉 Base64 的核心 */
var file = input_file.files[0];
// 這裡先判斷檔案類型,如果不是圖片就中止;把這段拿掉即可上傳任意檔案
if (!/image\/\w+/.test(file.type)) {
alert("請確認選擇的檔案為圖片類型");
return false;
}
var reader = new FileReader();
reader.onload = function () {
get_data(this.result);
};
reader.readAsDataURL(file);
} catch (e) {
alert('圖片轉 Base64 出錯啦!' + e.toString());
}
}
}
$(function () {
$("input").change(function () {
run(this, function (data) {
$('img').attr('src', data);
$('textarea').val(data);
});
});
});
</script>
</head>
<body>
<input type="file">
<hr>
<img style="max-height: 300px; height: 8em; min-width:8em;">
<hr>
<textarea style="display: block; width: 100%;height: 30em;"></textarea>
</body>
</html>
實際操作時只要選一張圖片,下方的 <img> 會立刻預覽,<textarea> 則會顯示完整的 Base64 字串,複製起來就能直接貼進任何地方。
data:[MIME 類型][;charset=][;base64],
實際看起來會像這樣:
data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL....
.demoImg {
background-image: url("data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL....");
}
<img width="40" height="30" src="data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...." />