要在上傳前得知圖片尺寸(例如檢查縮圖是否符合規格),最可靠的方式是在瀏覽器裡真的載入它一次。過去各家瀏覽器做法五花八門,現在用 URL.createObjectURL 就能統一處理,Firefox 與 Chrome 都支援。
<!doctype html>
<html>
<head>
<meta charset="GBK" />
<title>取得圖片寬高</title>
</head>
<body>
<script>
function newimage(obj) {
var objectURL = window.URL.createObjectURL(obj.files[0]);
var img = document.getElementById('img');
img.src = objectURL;
img.onload = function () {
alert(img.width);
alert(img.height);
};
}
</script>
<input id="idcardfile" type="file" name="idcardfile" onchange="newimage(this)" />
<img id="img" style="display: none;" />
</body>
</html>
createObjectURL 會為本機的 File 物件產生一個暫時的 blob URL,格式類似 blob:https://example.com/xxxx-xxxx。這個 URL 可以直接餵給 img,讓瀏覽器在不上傳的情況下解讀圖片,讀完之後 img.width 與 img.height 就是原始尺寸。
第一,onload 要早一點掛。實務上更穩妥的寫法是先註冊 onload,再指定 src:
img.onload = function () { ... };
img.src = objectURL;
因為如果圖片來自快取,載入可能在你設完 src 的那一刻就已完成,後掛的 onload 就不會觸發。
第二,用完要釋放。blob URL 會佔用記憶體,直到文件卸載才自動回收。若頁面會反覆預覽大量圖片,記得在 onload 結束後呼叫:
URL.revokeObjectURL(objectURL);
另外提醒一下,隱藏用的 display: none 不影響尺寸讀取——瀏覽器仍會完整解碼圖片,只是不繪製。這點和某些「元素必須可見才量得到尺寸」的情境不同,不必擔心。