2016-09-21 2 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;

このプロパティを使用できますあなたがCSSでimgを壊したにもかかわらず、imgの実際の高さと幅

+0

提案ありがとうしかし、私の問題を引き起こしていることを知っていますか? –

0

あなたがアップロードしている画像がpngに変換されていることを指摘したいだけです。
アップロードされたファイルは、ブロブを送信し、もはやところで

を選択したユーザーと同じであることであるbase64文字列をアップロードし、その後、より良いです〜あなたは、古いブラウザで canvas.toBlob(...)のサポートを得るために、この polyfillを使用することができ、より大きな3倍

これは、あなたが何をしているか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>

関連する問題