在圖片上傳預覽、響應式圖片載入、Canvas 繪圖、列印排版等場景,需要在圖片**完全載入前**或**載入瞬間**取得其原始尺寸 (naturalWidth/naturalHeight)。本文解析各種取得時機的差異、跨瀏覽器相容寫法、以及非同步封裝模式。
| 屬性 | 含義 | 可用時機 | 備註 |
|---|---|---|---|
img.naturalWidth |
圖片原始寬度 (像素) | onload 觸發後 |
HTML5 標準,IE9+ |
img.naturalHeight |
圖片原始高度 | onload 觸發後 |
同上 |
img.width |
顯示寬度 (受 CSS/屬性影響) | 隨時 | 可能被 CSS 縮放 |
img.height |
顯示高度 | 隨時 | 同上 |
img.clientWidth |
渲染盒模型寬度 (含 padding) | 渲染後 | 佈局計算用 |
function getImageNaturalSize(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({
width: img.naturalWidth,
height: img.naturalHeight,
aspectRatio: img.naturalWidth / img.naturalHeight
});
};
img.onerror = () => {
reject(new Error(`圖片載入失敗: ${src}`));
};
// 關鍵:設置 src 觸發載入
img.src = src;
});
}
// 使用範例
getImageNaturalSize('photo.jpg')
.then(({ width, height, aspectRatio }) => {
console.log(`原始尺寸: ${width}x${height}, 比例: ${aspectRatio.toFixed(2)}`);
// 可用於:決定縮圖尺寸、Canvas 繪圖比例、CSS aspect-ratio 設定
})
.catch(err => console.error(err));
function getImageSizeFromFile(file) {
return new Promise((resolve, reject) => {
// 1. 建立 Blob URL (不讀取檔案內容到記憶體,效能佳)
const objectUrl = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
// 2. 立即釋放 Blob URL (關鍵!避免記憶體洩漏)
URL.revokeObjectURL(objectUrl);
resolve({
width: img.naturalWidth,
height: img.naturalHeight,
aspectRatio: img.naturalWidth / img.naturalHeight,
fileSize: file.size,
fileName: file.name
});
};
img.onerror = () => {
URL.revokeObjectURL(objectUrl);
reject(new Error('圖片格式不支援或損壞'));
};
img.src = objectUrl;
});
}
// 完整上傳驗證流程
document.getElementById('file-input').addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file || !file.type.startsWith('image/')) return;
try {
const { width, height, aspectRatio } = await getImageSizeFromFile(file);
// 業務邏輯驗證
if (width < 800 || height < 600) {
throw new Error('圖片解析度過低,需至少 800x600');
}
if (aspectRatio > 2 || aspectRatio < 0.5) {
throw new Error('圖片長寬比需在 1:2 到 2:1 之間');
}
// 通過驗證,顯示預覽
showPreview(file);
} catch (err) {
alert(err.message);
e.target.value = ''; // 清空輸入
}
});
瀏覽器在下載圖片 Header 階段就能解析尺寸,無需下載完整檔案。但標準 API 無直接暴露此事件,需輪詢檢查:
function getImageSizeEarly(src, checkInterval = 50) {
return new Promise((resolve, reject) => {
const img = new Image();
let checkTimer;
img.onload = () => {
clearInterval(checkTimer);
resolve({ width: img.naturalWidth, height: img.naturalHeight });
};
img.onerror = () => {
clearInterval(checkTimer);
reject(new Error('載入失敗'));
};
// 輪詢檢查 naturalWidth 是否已可用 (0 表示未解析出尺寸)
checkTimer = setInterval(() => {
if (img.naturalWidth > 0 && img.naturalHeight > 0) {
clearInterval(checkTimer);
// 這裡不 resolve,讓 onload 統一處理,確保圖片完整可用
// 若極度追求速度可在此 resolve 並 img.src = '' 取消下載
}
}, checkInterval);
img.src = src;
});
}
// 圖片已在 DOM 中且完成載入
const img = document.getElementById('my-image');
if (img.complete && img.naturalWidth > 0) {
// 已載入完成,同步取得
console.log(img.naturalWidth, img.naturalHeight);
} else {
// 尚未載入完成,需等待
img.addEventListener('load', () => {
console.log(img.naturalWidth, img.naturalHeight);
}, { once: true });
}
// 批次處理頁面所有圖片
document.querySelectorAll('img[data-need-size]').forEach(img => {
if (img.complete) processImage(img);
else img.addEventListener('load', () => processImage(img), { once: true });
});
function processImage(img) {
const { naturalWidth, naturalHeight } = img;
// 設定 CSS aspect-ratio 保持比例防止佈局位移 (CLS)
img.style.aspectRatio = `${naturalWidth} / ${naturalHeight}`;
}
function getImageSizeLegacy(src, callback) {
const img = new Image();
// IE 使用 onreadystatechange
img.onreadystatechange = function() {
if (this.readyState === 'complete') {
// IE 某些版本 naturalWidth 不存在,用 width/height (需確保未被 CSS 縮放)
const w = img.naturalWidth || img.width;
const h = img.naturalHeight || img.height;
callback(null, { width: w, height: h });
}
};
img.onload = function() {
// 現代瀏覽器走這裡
callback(null, { width: img.naturalWidth, height: img.naturalHeight });
};
img.onerror = () => callback(new Error('載入失敗'));
img.src = src;
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 取得寬高為 0 | 在 onload 前讀取、或圖片載入失敗 |
確保在 onload/complete 後讀取,檢查 naturalWidth > 0 |
CSS 縮放導致 width/height 不準 |
CSS 設定 width: 100% 或 max-width |
永遠使用 naturalWidth/naturalHeight |
| Blob URL 記憶體洩漏 | 未呼叫 URL.revokeObjectURL() |
onload 立即撤銷,或頁面卸載時批次清理 |
| SVG 圖片無 naturalWidth | 向量圖無固有像素尺寸 | 檢查 file.type === 'image/svg+xml',需指定顯示尺寸或用 viewBox |
| 跨域圖片 (CORS) 無法讀取 | 安全策略限制 | 圖片伺服器需設定 Access-Control-Allow-Origin,或同域代理 |
<link rel="preload" as="image" href="hero.jpg">aspect-ratio CSS 或預留空間IntersectionObserver 只在進入視窗時檢測取得圖片原始尺寸的關鍵在於:使用 naturalWidth/naturalHeight、在 onload 後讀取、善用 URL.createObjectURL() 處理 File 物件、並務必 revokeObjectURL() 釋放記憶體。封裝為 Promise 介面可輕鬆整合現代 async/await 流程,滿足上傳驗證、響應式載入、Canvas 操作等多樣需求。