IOS6已经发布,我一直在测试照片上传。
它运行良好,但对于超过 3G 的较大图像,它的速度如预期的那样慢。
借助 File API 和 Canvas,可以使用 JavaScript 调整图像大小。我希望,如果我在尝试上传图像之前调整图像大小,它们的上传速度会更快,从而提供快速的用户体验。随着智能手机处理器的改进速度快于网络速度,我相信该解决方案是赢家。
Nicolas 提供了一个出色的图像调整解决方案:
但是,我在使用 jQuery 的 Ajax 实现它时遇到了最困难的时候。感谢任何建议或帮助,因为此代码可能对于 IOS6 后的移动 Web 应用程序开发非常有用。
var fileType = file.type,
reader = new FileReader();
reader.onloadend = function () {
var image = new Image();
image.src = reader.result;
image.onload = function () {
//Detect image size
var maxWidth = 960,
maxHeight = 960,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
} else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
//Create canvas with new image
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(fileType);
if (formdata) {
formdata.append("images[]", finalFile);
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
dataType: 'json',
processData: false,
contentType: false,
success: function (res) {
//successful image upload
}
});
}
}
}
reader.readAsDataURL(file);
最佳答案
我刚刚开发了一个用于客户端 canvas 图像大小调整的 jQuery 插件。 它还可以处理方向和iOS6 挤压图像问题。
您可以尝试: http://gokercebeci.com/dev/canvasresize
用法:
$.canvasResize(file, {
width : 300,
height : 0,
crop : false,
quality : 80,
callback: function(dataURL, width, height){
// your code
}
});
关于ajax - IOS6 和 Safari 照片上传 - 文件 API + Canvas + jQuery Ajax 异步上传和调整文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12539862/