我刚刚开始学习JavaScript。我正在尝试在上传到服务器之前,使用HTML5 Canvas对图像进行客户端大小调整并存储。我已经找到了一种方法:使用HTML5 Canvas,详情请见http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
然而,我的问题是:上传的是空白图像。我认为这是画布没有完成绘制就从画布中抓取图像的原因。当我设置3秒的窗口超时,然后再从画布中抓取图像,一切正常。有没有比超时更可靠的方法?或者还有其他方法可以在客户端调整图像大小?
我之所以要进行客户端图片调整大小,是因为我遇到了上传不必要大文件的人,我认为在客户端调整图像大小是最有效的方式。
谢谢您提供任何提示/答案!
我之所以要进行客户端图片调整大小,是因为我遇到了上传不必要大文件的人,我认为在客户端调整图像大小是最有效的方式。
谢谢您提供任何提示/答案!
//resize image
Resizeimage.resize(file);
//***if i wrap this part with timeout it works
var canvas = document.getElementById('canvas');
var data = canvas.toDataURL(file.type);
// convert base64/URLEncoded data component to raw binary data held in a string
var bytestring;
if (data.split(',')[0].indexOf('base64') >= 0)
bytestring = atob(data.split(',')[1]);
else
bytestring = escape(data.split(',')[1]);
//get imagetype
var mimeString = data.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(bytestring.length);
for (var i = 0; i < bytestring.length; i++) {
ia[i] = bytestring.charCodeAt(i);
}
// create a blob from array
var blob = new Blob([ia], {
type: mimeString
});
//upload files
$scope.upload = $upload.upload({
url: 'articles/imageUpload',
method: 'POST',
file: blob
//update progress bar
}).progress(function(event) {
$scope.uploadInProgress = true;
$scope.uploadProgress = Math.floor(event.loaded / event.total * 100);
//file upload success
}).success(function(data, status, headers, config) {
$scope.uploadInProgress = false;
$scope.uploadedImage = JSON.parse(data);
$scope.isDisabled = false;
//file upload fail
}).error(function(err) {
$scope.uploadInProgress = false;
console.log('Error uploading file: ' + err.message || err);
});
//***
angular.module('articles').factory('Resizeimage', [
function() {
var imgSelectorStr = null;
// Resizeimage service logic
function render(src) {
var image = new Image();
image.onload = function() {
var canvas = document.getElementById('canvas');
//check the greater out of width and height
if (image.height > image.width) {
image.width *= 945 / image.height;
image.height = 945;
} else {
image.height *= 945 / image.width;
image.width = 945;
}
//draw (&resize) image to canvas
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
};
image.src = src;
}
function loadImage(src) {
// Create fileReader and run the result through the render
var reader = new FileReader();
reader.onload = function(e) {
render(e.target.result);
};
reader.readAsDataURL(src);
}
// Public API
return {
resize: function(src) {
loadImage(src);
return true;
}
};
}
]);