一、将圖檔轉成icon碼的實作方式
html代碼:
js代碼//圖檔預覽功能
function previewImage(file,imgNum)
{
var MAXWIDTH = 200;
var MAXHEIGHT = 200;
var div = document.getElementById('preview'+imgNum);
if (file.files && file.files[0])
{
div.innerHTML ='';
var img = document.getElementById('imghead'+imgNum+'');
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 //
{
var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
file.select();
var src = document.selection.createRange().text;
div.innerHTML = '';
var img = document.getElementById('imghead2');
img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
div.innerHTML = "
}
}
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
var param = {top:0, left:0, width:width, height:height};
if( width>maxWidth || height>maxHeight )
{
rateWidth = width / maxWidth;
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;
}
二、使用js的另一種方法一次選中多個圖檔預覽展示
測試頁面
//下面用于多圖檔上傳預覽功能
function setImagePreviews(avalue) {
var docObj = document.getElementById("doc");
var dd = document.getElementById("dd");
dd.innerHTML = "";
var fileList = docObj.files;
for (var i = 0; i < fileList.length; i++) {
dd.innerHTML += "
";
var imgObjPreview = document.getElementById("img"+i);
if (docObj.files && docObj.files[i]) {
//火狐下,直接設img屬性
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '150px';
imgObjPreview.style.height = '180px';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式擷取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]);
}
else {
//IE下,使用濾鏡
docObj.select();
var imgSrc = document.selection.createRange().text;
alert(imgSrc)
var localImagId = document.getElementById("img" + i);
//必須設定初始大小
localImagId.style.width = "150px";
localImagId.style.height = "180px";
//圖檔異常的捕捉,防止使用者修改字尾來僞造圖檔
try {
localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch (e) {
alert("您上傳的圖檔格式不正确,請重新選擇!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
}
return true;
}
相關标簽:js
本文原創釋出php中文網,轉載請注明出處,感謝您的尊重!