2012-01-18 43 views
76

之前,我有一個JPS在其中一個用戶可以把圖像的形式:檢查圖像的寬度和高度上載的JavaScript

<div class="photo"> 
    <div>Photo (max 240x240 and 100 kb):</div> 
    <input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/> 
</div> 

我寫了這個JS:

function checkPhoto(target) { 
    if(target.files[0].type.indexOf("image") == -1) { 
     document.getElementById("photoLabel").innerHTML = "File not supported"; 
     return false; 
    } 
    if(target.files[0].size > 102400) { 
     document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)"; 
     return false; 
    } 
    document.getElementById("photoLabel").innerHTML = ""; 
    return true; 
} 

其中工程罰款檢查文件類型和大小。現在我想檢查圖像的寬度和高度,但我不能這樣做。
我試過target.files[0].width,但我得到undefined。用其他方式我得到0
有什麼建議嗎?

+0

你的意思是JPG? – SaidbakR

回答

154

該文件只是一個文件,你需要像這樣創建的圖像:

var _URL = window.URL || window.webkitURL; 
$("#file").change(function (e) { 
    var file, img; 
    if ((file = this.files[0])) { 
     img = new Image(); 
     img.onload = function() { 
      alert(this.width + " " + this.height); 
     }; 
     img.src = _URL.createObjectURL(file); 
    } 
}); 

演示:http://jsfiddle.net/4N6D9/1/

我想你知道這是隻在少數瀏覽器支持。主要是firefox和chrome,現在可能也是歌劇。

+0

它像一個魅力,謝謝你。 – Simon

+0

在safari版本5.1.7中不起作用 – Diffy

+1

除非您有safari 6.0,否則它絕對不能用於safari。 6.0是目前支持文件API的唯一版本。而且我不認爲蘋果會爲Windows發佈6.0。 5.1.7已經是很久以前的safari的最新版本 –

10

我同意。一旦它被上傳到用戶的瀏覽器可以訪問的地方,那麼獲取該尺寸是相當容易的。由於您需要等待圖像加載,因此您需要掛入imgonload事件。

var width, height; 

var img = document.createElement("img"); 
img.onload = function() { 
    // `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height 
    // The natural size is the actual image size regardless of rendering. 
    // The 'normal' width/height are for the **rendered** size. 

    width = img.naturalWidth || img.width; 
    height = img.naturalHeight || img.height; 

    // Do something with the width and height 
} 

// Setting the source makes it start downloading and eventually call `onload` 
img.src = "http://your.website.com/userUploadedImage.jpg"; 
+1

有一個錯誤 - 它應該是img.naturalHeight不只是naturalHeight。不幸的是,我無法編輯,因爲它表示編輯必須至少有6個字符長。 –

+0

謝謝@Juris。我修好了它。 – pseudosavant

2

在我看來,你必須要求完美的答案是

var reader = new FileReader(); 
    //Read the contents of Image File. 
    reader.readAsDataURL(fileUpload.files[0]); 
    reader.onload = function (e) { 
    //Initiate the JavaScript Image object. 
    var image = new Image(); 

    //Set the Base64 string return from FileReader as source. 
         image.src = e.target.result; 

         //Validate the File Height and Width. 
         image.onload = function() { 
          var height = this.height; 
          var width = this.width; 
          if (height > 100 || width > 100) { 
           alert("Height and Width must not exceed 100px."); 
           return false; 
          } 
          alert("Uploaded image has valid Height and Width."); 
          return true; 
         }; 

        }