上傳頭像時能先看一眼效果,是體驗上很實用的小功能。難點在於瀏覽器差異:現代瀏覽器可以用 FileReader 讀取本地文件,舊版 IE 則只能靠 filter 加 document.selection 拿到路徑。
<style type="text/css">
#preview {
width:100px; height:100px;
border:1px solid #000; overflow:hidden;
}
#imghead {
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);
}
</style>
function previewImage(file) {
var MAXWIDTH = 100;
var MAXHEIGHT = 100;
var div = document.getElementById('preview');
if (file.files && file.files[0]) {
// 現代瀏覽器:FileReader 讀成 dataURL
div.innerHTML = '<img id=imghead>';
var img = document.getElementById('imghead');
img.onload = function () {
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
img.style.marginLeft = rect.left + 'px';
img.style.marginTop = rect.top + 'px';
};
var reader = new FileReader();
reader.onload = function (evt) { img.src = evt.target.result; };
reader.readAsDataURL(file.files[0]);
}
else {
// 舊版 IE:無法直接讀取 dataURL,改用 AlphaImageLoader 滤镜
var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
file.select();
var src = document.selection.createRange().text;
div.innerHTML = '<img id=imghead>';
var img = document.getElementById('imghead');
img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
div.innerHTML = "<div id=divhead style='width:" + rect.width +
"px;height:" + rect.height + "px;margin-top:" + rect.top +
"px;margin-left:" + rect.left + "px;" + sFilter + src + "\"'></div>";
}
}
// 計算等比縮放後的尺寸與居中偏移
function clacImgZoomParam(maxWidth, maxHeight, width, height) {
var param = { top: 0, left: 0, width: width, height: height };
if (width > maxWidth || height > maxHeight) {
var rateWidth = width / maxWidth;
var rateHeight = height / maxHeight;
if (rateWidth > rateHeight) {
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
} else {
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}
<div id="preview">
<img id="imghead" width="100" height="100" border="0" src="../images/head01_big.jpg">
</div>
<br/>
<input type="file" onchange="previewImage(this)" />
img.onload 一定要在設置 src 之前綁定,否則小圖在緩存中時可能錯過事件。document.selection.createRange().text 取得本地路徑,這個值不一定要拼接 URL 編碼,但路徑含中文時可能出現亂碼。URL.createObjectURL(file) 一行就能得到可顯示的臨時地址,用完記得 URL.revokeObjectURL() 釋放;樣式上直接用 object-fit: cover 代替手寫縮放計算。