IOS6和Safari Photo Uploading – 文件API + Canvas + jQuery Ajax异步上传和调整文件大小

IOS6已经发布,我一直在测试照片上传。

它效果很好,但是通过3G上的图像越大,它就像预期的那样缓慢。

感谢File API和Canvas,可以使用JavaScript调整图像大小。 我希望如果我在尝试上传之前调整图像大小,它们会更快上传 – 这样可以提高用户体验。 随着智能手机处理器以比网络速度快的速度增长,我相信这个解决方案是一个胜利者。

Nicolas为图像大小调整提供了出色的解决方案:

图像在上传前resize

但是,我最难用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 } }); 

自第二个iOS6测试版发布以来,我一直在使用上传function。 以下代码适用于我:

把它放在HTML页面的头部 –

  

这是HTML –

  

这是PHP –

  

我遇到的唯一问题是从相机加载图像而不旋转90度。

希望这会有所帮助,如果您对代码有任何问题,请告诉我(这是我的第一篇文章)。

鉴于我们正在处理移动浏览器上的大图像和内存问题,我想看看是否可以找到轻量级解决方案,避免创建重复的canvas并执行其他图像操作,仅用于检测和resize。

似乎Mobile Safari垂直挤压一个太大的图像,它所用的比例保持不变。

所以在我甚至在canvas上渲染图像之前,我使用了一个非常快速的经验法则,我只需检查浏览器是否是移动iDevice navigator.userAgent.match(/(iPod|iPhone|iPad)/) ..并且图像的高度或宽度大于2000像素,在这种情况下我知道它会被压扁。 在这种情况下,在canvasContext.drawImage()我指定图像高度比给定图像大小调整目标通常应该高4倍。 基于我所看到的,Mobile Safari将图像压缩了4倍。

然后我渲染图像,它第一次呈现未扭曲,将预拉伸的图像压缩回原来的X:Y比例。 没有任何额外的canvas元素或上下文或测试渲染或像素迭代,使用上面提到的100%解决方案。

我确信可能存在一些边缘情况,并且图像大小限制可能不准确,但对于我的应用程序,我想要一个快速的解决方案。