Ответ 1
Попробуйте что-то вроде этого:
function resize(file, max_width, max_height, compression_ratio, imageEncoding){
var fileLoader = new FileReader(),
canvas = document.createElement('canvas'),
context = null,
imageObj = new Image(),
blob = null;
//create a hidden canvas object we can use to create the new resized image data
canvas.id = "hiddenCanvas";
canvas.width = max_width;
canvas.height = max_height;
canvas.style.visibility = "hidden";
document.body.appendChild(canvas);
//get the context to use
context = canvas.getContext('2d');
// check for an image then
//trigger the file loader to get the data from the image
if (file.type.match('image.*')) {
fileLoader.readAsDataURL(file);
} else {
alert('File is not an image');
}
// setup the file loader onload function
// once the file loader has the data it passes it to the
// image object which, once the image has loaded,
// triggers the images onload function
fileLoader.onload = function() {
var data = this.result;
imageObj.src = data;
};
fileLoader.onabort = function() {
alert("The upload was aborted.");
};
fileLoader.onerror = function() {
alert("An error occured while reading the file.");
};
// set up the images onload function which clears the hidden canvas context,
// draws the new image then gets the blob data from it
imageObj.onload = function() {
// Check for empty images
if(this.width == 0 || this.height == 0){
alert('Image is empty');
} else {
context.clearRect(0,0,max_width,max_height);
context.drawImage(imageObj, 0, 0, this.width, this.height, 0, 0, max_width, max_height);
//dataURItoBlob function available here:
// http://stackoverflow.com/questions/12168909/blob-from-dataurl
// add ')' at the end of this function SO dont allow to update it without a 6 character edit
blob = dataURItoBlob(canvas.toDataURL(imageEncoding));
//pass this blob to your upload function
upload(blob);
}
};
imageObj.onabort = function() {
alert("Image load was aborted.");
};
imageObj.onerror = function() {
alert("An error occured while loading image.");
};
}
Обратите внимание:
Работа с файловыми загрузчиками и загрузка изображений означает, что есть некоторые задержки, и поэтому функция асинхронна, поэтому попытка просто вернуть данные blob не будет работать. Вам нужно дождаться загрузки, прежде чем вы сможете использовать загруженные данные и отключить вызов вашей функции загрузки для файла EACH.
Кроме того, у файлового загрузчика могут быть проблемы с совместимостью с браузером, но я не думаю, что это возможно на любой другой стороне клиента.