从app页面选择手机中的图片一般都比较大,动则N个M,然后页面就挂在那里玩了,接下来就是讨论解决方案,之道的img压缩方案就是使用canvas压缩图片,那现在问题变为canvas压缩图片后如何上传的问题了
1、从input file中读出图片的方法

View Code JAVASCRIPT
1
2
3
4
5
6
7
var loadImageFromFile = function(file, callback) {
    var reader = new FileReader();
    reader.onload = function (e) {
        callback(e.target.result);
    };
    reader.readAsDataURL(file);
};

参考链接:https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/

2、使用canvas压缩图片同上链接已给出

3、canvas转为blob格式

View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var dataURItoBlob = function(dataURI){
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
 
    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
};

参考链接:http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata

4、异步上传,新建一个formdata对象,添加blob到formdata中

View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var formdata = new FormData();
formdata.append('imgfile', blob);
 
var url = "upload.php";
$.ajax({
    type:'POST',
    url:url,
    data:formdata,
    contentType:false,
    processData:false,
    success : function(jdata){
        console.log(jdata);
    }
});

综上所述给一个Helper

View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var ScaleImageHelper = {
    //从FILE中加载img
    loadImageFromFile : function(file, callback) {
        var reader = new FileReader();
        reader.onload = function (e) {
            callback(e.target.result);
        };
        reader.readAsDataURL(file);
    },
 
    dataURItoBlob : function(dataURI){
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);
 
        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
 
        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
 
        return new Blob([ia], {type:mimeString});
    },
 
    resizeImgToCanvas : function(img, maxHeight, maxWidth){
        maxHeight = maxWidth||640;
        maxWidth = maxWidth||640;
        var width = img.width;
        var height = img.height;
 
        if(width > height){
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        }else{
            if (height > maxHeight) {
                width *= maxHeight / height;
                height = maxHeight;
            }
        }
 
        var canvas = document.createElement('canvas')
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        return canvas;
    },
 
    canvasToBlob : function(canvas){
        var dataURL = canvas.toDataURL('image/jpeg', 0.5);
        return this.dataURItoBlob(dataURL);
    },
 
    post : function(url, formdata, callback){
        $.ajax({
            type:'POST',
            url:url,
            data:formdata,
            contentType:false,
            processData:false,
            success : function(jdata){
                console.log(jdata);
            }
        });
    }
};

测试案例如下:

1
<input type="file" id="J-file" accept="image/*">
View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//监听文件变化
$('#J-file').on('change', function(){
    if(this.files.length<1){
        return ;
    }
    var file = this.files[0];
    //从文件中加载图片
    ScaleImageHelper.loadImageFromFile(file, function(src){
        var img = document.createElement('img');
        //插入图片到body中
        //$(document.body).append(img);
        //图片加载完成
        img.onload = function(){
            //通过canvas缩放图片
            var canvas = ScaleImageHelper.resizeImgToCanvas(this, 10, 10);
            //把canvas转成blob格式
            var blob = ScaleImageHelper.canvasToBlob(canvas);
 
            //插入到form中异步上传
            var formdata = new FormData();
            formdata.append('imgfile', blob);
            ScaleImageHelper.post('./scale-canvas.php', formdata);
        };
        img.src = src;
    });
});