DIV CSS 佈局教程網

用 JavaScript 實作點擊縮圖看原圖,以及本地上傳即時預覽
編輯:關於JavaScript     

直接上程式碼。以下示範兩段實作:一是點擊圖片後依原圖尺寸重新縮放顯示,二是選擇本地檔案後在頁面上即時預覽。

一、點擊圖片顯示原圖

 function DrawImage(ImgD){
  var image = new Image();
  image.src=ImgD.src;
  var width = $(ImgD).attr("width");
  var height = $(ImgD).attr("height");
  if(width >100 && height>80){
    ImgD.width=100;
    ImgD.height=80;
    ImgD.alt=image.width+"×"+image.height;
  }else{
    if(image.width>0 && image.height>0){
      flag=true;
      if(image.width>300 || image.height>200){
        ImgD.width=image.width/2;
        ImgD.height=image.height/2;
        ImgD.alt=image.width+"×"+image.height;
      }else{
        ImgD.width=image.width;
        ImgD.height=image.height;
        ImgD.alt=image.width+"×"+image.height;
      }
    }
  }
}

這段邏輯的運作順序值得說明一下:先用 new Image() 讀取真實尺寸,再回頭調整畫面上那張 <img> 的寬高。若元素本來就被限制在 100×80 以內,就放大到 100×80;否則看原圖是否超過 300×200,超過就縮成一半,沒超過就還原成原始尺寸。同時把真實尺寸寫進 alt,讓使用者能知道原圖有多大。

實務上有兩點建議:其一,这种做法每次點擊都會在同一個元素上反覆切換尺寸,若想要更好的體驗,通常會改用 lightbox 之類的彈層方案;其二,width/height 透過 jQuery 的 attr() 讀取,在某些情境下會拿到空值,改用 ImgD.width 直接取屬性會更穩妥。

二、上傳圖片即時預覽

下面這份範例做到「選檔後立刻在頁面上看到縮圖」,並按比例縮放以適應固定尺寸的預覽框。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>圖片上傳本地預覽</title>
<style type="text/css">
#preview{width:260px;height:190px;border:1px solid #000;overflow:hidden;}
#imghead {filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);}
</style>
<script type="text/javascript">
//圖片上傳預覽 IE是用了濾鏡。
function previewImage(file) {
  var MAXWIDTH = 260;
  var MAXHEIGHT = 180;
  var div = document.getElementById('preview');
  if (file.files && file.files[0]) {
    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
  {
    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);
    status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
    div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"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 ) {
    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;
}
</script>
</head>
<body>
<div id="preview">
<img id="imghead" width=100 height=100 border=0 src='<%=request.getContextPath()%>/images/defaul.jpg'>
</div>
<input type="file" onchange="previewImage(this)" />
</body>
</html>

重點說明

clacImgZoomParam() 是這段的靈魂。它接收容器上限與圖片實際尺寸,先判斷是否需要縮放;若需要,就分別算出寬與高的縮放比例,取較大的那個當作基準,這樣才能保證圖片完整塞進框內而不變形。最後再計算 left 與 top,讓圖片在框中置中。

FileReader 是現代寫法。透過 readAsDataURL() 把檔案讀成 base64 資料 URL,直接塞給 img.src,全程不必上傳到伺服器。

程式碼中那段 AlphaImageLoader 濾鏡屬於 IE 舊版的相容分支。以今天的環境來看,IE 早已退場,這段可以安全移除,只保留 FileReader 路徑即可讓程式碼短掉一半以上。同理,範例裡的 document.selection.createRange() 也只在 IE 有效。

還有一個容易忽略的細節:圖片尺寸必須在 onload 之後才讀取,否則 offsetWidth 會是 0。範例已正確處理,但自行改寫時經常有人漏掉這一步,導致縮放計算全錯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved