2016-09-21 108 views
0

我:如何在javascript中獲取文件api圖片大小?

if(window.FileReader) { 
    reader = new FileReader(); 
    var sendingcontext = sendingcanvas.getContext('2d'); 
    reader.onload = (function(theFile) { 
    var image = new Image(); 
    image.src = theFile.target.result; 

    image.onload = function() { 
    sendingcanvas.width=this.width; 
    sendingcanvas.height= this.height; 
    console.log("height: " + sendingcanvas.height + " width: " + sendingcanvas.width) 
     sendingcontext.drawImage(image, 0,0); 
    }; 
     }); 
     reader.onloadend = function(e){ 
     showUploadedItem(e.target.result, file.fileName); 
    } 
    reader.readAsDataURL(file); 
    alert(sendingcanvas.toDataURL()); 
} 

我想我不必解釋代碼做什麼,但我要的是獲取文件API圖像的高度和寬度,將其設置爲sendingcanvas並將其發送到服務器使用ajax通過使用它toDataURL()。我知道這很奇怪,但如果我從我的腳本中刪除alert(sendingcanvas.toDataURL())我的服務器收到一個空的圖像,但如果我在我的腳本中有它在我的服務器中,圖像正是客戶端擁有它的方式。

謝謝你的一切。

+0

您真的確定要轉換圖像與一個PNG質量+元信息損失? – Endless

回答

0

你可以嘗試讓在<img>標籤的圖像和獲取圖像的實際寬度和大小的情況下,你有一個DOM什麼:

var height = $("#main-reference").get(0).naturalWidth; 
 
var width = $("#main-reference").get(0).naturalHeight;

這個屬性給你真正的高度和寬度的IMG雖然你已經打破了IMG與CSS

+0

感謝您的建議但是你知道是什麼導致我的問題嗎? –

0

只是想指出,你正在上傳的圖像正在轉換爲PNG(如果這是你想要的)
上傳的文件不再一樣選擇

者均基於用戶,發送一個blob是更好然後上傳一個base64字符串,它是〜3倍大,你可以使用這個polyfill在舊的瀏覽器以獲取canvas.toBlob(...)支持

這是basicly你在做什麼:

function showUploadedItem(image){ 
 
    document.body.appendChild(image) 
 
} 
 

 
// Simulate a file (image) 
 
var black_1x1 = new Uint8Array([71,73,70,56,57,97,1,0,1,0,128,0,0,5,4,4,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59]) 
 
var file = new Blob([black_1x1], {type:"image/gif"}) 
 

 
console.log(file) 
 

 
var img = new Image 
 
img.onload = function() { 
 
    console.log("height: " + this.height + " width: " + this.width) 
 

 
    var canvas = document.createElement('canvas') 
 
    var ctx = canvas.getContext('2d') 
 
    canvas.width = this.width 
 
    canvas.height = this.height 
 
    showUploadedItem(this) 
 
    ctx.drawImage(this, 0, 0) 
 
    canvas.toBlob(function(blob){ 
 
    console.log(blob) 
 
    // Send the canvas pic to server (using fetch, xhr or jQuery 
 
    // With or without FormData 
 
    // fetch('/upload', {method: 'post', body: blob}) 
 
    }) 
 
} 
 
// No need to use fileReader + base64 
 
img.src = URL.createObjectURL(file)
/* Just to make the pixel more vissible */ 
 
body img { 
 
    width: 10px 
 
}
<!-- toBlob polyfill --> 
 
<script src="https://cdn.rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>