我正在尝试使用canvasResize()调整图像文件的大小,然后将文件对象转换为dataUrl图像大小(57x57)。我需要在服务器中上传大小(57x57)的图像。 任何想法将dataUrl图像转换为文件对象([对象文件])请帮助我。
<html>
<head>
<script src="jquery.js"></script>
<script>
function submit(){
var fileData = $('#Image').get(0).files[0];
alert(fileData);// look like ([object file]);
canvasResize(fileData, {
width: 57,
height: 57,
crop: false,
quality: 80,
//rotate: 90,
callback: function(data, width, height) {
console.log("source: "+data)
}
}
}
</script>
</head>
<body>
<input type="file" id="Image" onClick="javascript:submit();"/>
</body>
</html>
答案 0 :(得分:0)
首先,使用将您的图像文件绘制到57x57画布中,然后使用以下代码将dataurl转换为blob和ajax发送。
function readFileAsDataURL(blob, callback) {
var a = new FileReader();
a.onload = function(e) {callback(e.target.result);};
a.readAsDataURL(blob);
}
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
var fileObject = $('#Image')[0].files[0];
readFileAsDataURL(fileObject, function (dataurl){
var canvas = $('<canvas width=57 height=57></canvas>')[0];
var img = new Image();
img.onload = function (){
canvas.drawImage(img,0,0,57,57);
var dataurl = canvas.toDataURL('image/jpeg',0.8);
//var dataurl = canvas.toDataURL('image/png'); //if you need png
var blob = dataURLtoBlob(dataurl);
var fd = new FormData();
fd.append("myFile", blob, "thumb.jpg");
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.onload = function(){
alert('upload complete');
};
xhr.send(fd);
};
img.src = dataurl;
});