IOS6和Safari照片上传 – 文件API画布jQuery Ajax异步上传和调整文件大小

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

它的效果很好,但是在3G上的图像较大,它的SLOW是预期的.

感谢File API和Canvas,可以使用JavaScript调整图像大小.我希望如果我在尝试上传图片之前调整图像大小,那么上传速度会更快 – 借给用户体验更快.智能手机处理器的速度提升速度比网络速度快,相信这个解决方案是赢家.

尼古拉斯为图像调整大小提供了一个很好的解决方案:

Image resize before upload

但是,我正在用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,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);

解决方法

我刚刚开发了一个用于客户端画布图像调整大小的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和Safari照片上传 – 文件API画布jQuery Ajax异步上传和调整文件大小全部内容,希望文章能够帮你解决IOS6和Safari照片上传 – 文件API画布jQuery Ajax异步上传和调整文件大小所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。