2014-03-25 42 views
0

我嘗試使用下面的代碼圖片使用javascript

這是圖片上傳標籤

<input type="file" name="files" id="imgUpload" onchange="readURLBottom(this)" value="Select" > 
<ul id="logoPlaceholder"></ul> 

調整圖像大小調整問題,在Firefox和這是我使用的JavaScript代碼如下圖片大小調整

var objBottom, reader, imgData, maxHeight, maxWidth, imageHeight, imageWidth; 

function readURLBottom(input) 
{ 
    if (input.files && input.files[0]) 
    { 
     reader = new FileReader(); 
     reader.onload = function (e) 
     { 
      objBottom = new Image(); 
      objBottom.src = e.target.result; 

      imageHeight = objBottom.height; 
      imageWidth = objBottom.width; 

      if (imageWidth > maxWidth) 
      { 
       imageHeight = imageHeight/(imageWidth/maxWidth); 
       imageWidth = maxWidth; 
      } 

      var c = document.createElement('canvas'); 

      c.height = imageHeight; 
      c.width = imageWidth; 

      var ctx = c.getContext("2d"); 
      ctx.drawImage(objBottom, 0, 0, imageWidth, imageHeight); 

      objBottom.src = c.toDataURL(); 

      var strToAppend = '<li class="span3"><a class="thumbnail"><i onclick=RemoveImage(this) class="icon-remove pull-right"></i><img src="' + objBottom.src + '" width="100px"/></a></li><p></p>'; 
      $("#logoPlaceholder").html(strToAppend); 

     }; 

     reader.readAsDataURL(input.files[0]); 
    } 
} 

這在Chrome中正常工作。但是這不適用於Firefox。我在Firefox中爲以下兩個值取零。

imageHeight = objBottom.height; 
imageWidth = objBottom.width; 
+0

我假設你正試圖將一個大的圖像放入繪製在畫布上的縮略圖上。對? –

+0

其實我只是試圖從打開的文件對話框中上傳圖片。無論圖像的像素是較大還是較小,Firefox都會出現此問題 –

回答

0

嘗試使用您的代碼onload圖像對象。

objBottom = new Image(); 
objBottom.onload = function(){ 
    //Your code 
} 
objBottom.src = //set the source here 

還檢查控制檯是否有錯誤。

0

我已經過了相同的情況。

你可以試試這個:

imageHeight = objBottom.height; 
imageWidth = objBottom.width;  

if ((imageHeight==0)&&(imageWidth==0)){ //Firefox issue 
    readURLBottom(input); //recursive call 
} 

這對我的作品。我希望它能幫助你。