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

时间:2012-09-22 01:06:06

标签: ajax jquery ios6 fileapi

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

效果很好,但是通过3G上的图像比预期的要慢。

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

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

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, 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);

3 个答案:

答案 0 :(得分:31)

我刚开发了一个jQuery插件,用于客户端 canvas 图像大小调整。 它还处理方向 iOS6压缩图像问题。

您可以尝试: http://gokercebeci.com/dev/canvasresize

用法:

$.canvasResize(file, {
               width   : 300,
               height  : 0,
               crop    : false,
               quality : 80,
               callback: function(dataURL, width, height){

                         // your code

               }
});

答案 1 :(得分:7)

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

将它放在HTML页面的头部 -

<script>window.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");

var fileSelect = document.getElementById("fileSelect"),
    input = document.getElementById("input");

    input.addEventListener("change", handleFiles);

    //hides ugly default file input button  
    fileSelect.addEventListener("click", function (e) {
        if (input) {
            input.click();
        }
        e.preventDefault();
    }, false);

function handleFiles(e) {
    var reader = new FileReader;
    reader.onload = function (event) {
        var img = new Image();
        img.src = reader.result;
        img.onload = function () {
            var maxWidth = 320,
                maxHeight = 350,
                imageWidth = img.width,
                imageHeight = img.height;

            if (imageWidth > imageHeight) {
                if (imageWidth > maxWidth) {
                    imageHeight *= maxWidth / imageWidth;
                    imageWidth = maxWidth;
                }
            } else {
                if (imageHeight > maxHeight) {
                    imageWidth *= maxHeight / imageHeight;
                    imageHeight = maxHeight;
                }
            }
            canvas.width = imageWidth;
            canvas.height = imageHeight;

            ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

            // The resized file ready for upload
            var finalFile = canvas.toDataURL("image/png");

            var postData = 'canvasData=' + finalFile;
            var ajax = new XMLHttpRequest();
            ajax.open('POST', 'save.php', true);
            ajax.setRequestHeader('Content-Type', 'canvas/upload');

            ajax.onreadystatechange = function () {
                if (ajax.readyState == 4) {
                    //just to visually confirm it worked...
                    window.open(canvas.toDataURL("image/png"), "mywindow");
                }
            }
            ajax.send(postData);
        }
    }
    reader.readAsDataURL(e.target.files[0]);
}
}
</script>

这是HTML -

 <div style="width:320px;position:absolute;z-index:9;top:387px;">
<button style="width:60px;" id="fileSelect">upload</button>
<input type="file" id="input" name="input" accept="image/*" style="display:none;"></div>

这是PHP -

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data
   $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

   // Remove the headers (data:,) part.  
   // A real application should use them according to needs such as to check image type
   $filteredData=substr($imageData, strpos($imageData, ",")+1);

   // Need to decode before saving since the data we received is already base64 encoded
   $unencodedData=base64_decode($filteredData);

   // Save file.  This example uses a hard coded filename for testing, 
   // but a real application can specify filename in POST variable
   $fp = fopen( 'users/user_photo.png', 'wb' );
   fwrite( $fp, $unencodedData);
   fclose( $fp );
 }
 ?>

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

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

答案 2 :(得分:1)

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

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

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

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

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

相关问题