我有:
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 :(得分:0)
您可以尝试将图片放在<img>
标记中,并获取图片的实际宽度和大小,以防您拥有DOM:
var height = $( "#main-reference" ).get( 0 ).naturalWidth;
var width = $( "#main-reference" ).get( 0 ).naturalHeight;
这个属性为你提供了img的真实高度和宽度,尽管你用css打破了img
答案 1 :(得分:0)
只是想指出您正在上传的图片正在转换为png(如果这是你想要的)
上传的文件不再与用户选择的相同
顺便说一下,发送一个blob比上传一个大约3倍的base64字符串更好,你可以使用这个polyfill来获得旧浏览器中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)
&#13;
/* Just to make the pixel more vissible */
body img {
width: 10px
}
&#13;
<!-- toBlob polyfill -->
<script src="https://cdn.rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>
&#13;