簡體   English   中英

如何在JavaScript中獲取文件api圖像大小?

[英]How to get file api image size in javascript?

我有:

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 ,然后使用toDataURL()使用ajax將其發送到服務器。 我知道這很奇怪,但是如果我從腳本中刪除了alert(sendingcanvas.toDataURL()) ,我的服務器會收到一個空圖像,但是如果我的腳本中包含該圖像,則該圖像正是客戶端所擁有的圖像。

謝謝你所做的一切。

您可以嘗試將圖像放在<img>標記中,以獲取圖像的實際寬度和大小,以防萬一您擁有DOM:

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

該屬性為您提供了img的實際高度和寬度,盡管您已經用css破壞了img

只是要指出您正在上傳的圖像已被轉換為png(如果您要的是)
上傳的文件不再與所選用戶相同

順便說一句,送斑點是更好然后上傳一個base64字符串,它是〜3倍大,你可以使用這個填充工具以獲取支持canvas.toBlob(...)在舊的瀏覽器

基本上,這就是您正在執行的操作:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM