首页 > 代码库 > 网页裁剪图片(FileAPI)

网页裁剪图片(FileAPI)

网页端裁剪图片(FileAPI),兼容谷歌火狐IE6/7/8。
高版本浏览器用canvas 裁剪,低版本用flash过度。
FileAPI 的应用实例。

效果

 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
var ImgCropUtil = function(config) {
 
    var imgos = config.imgos;
    var cropMain = config.cropMain;
    var imgPreviewWidth = config.imgPreviewWidth;
    var ratio = 0;
 
    function getRatio(imgorigin, imgafter) {
        return imgafter.width / imgafter.height > imgorigin.width / imgorigin.height ? imgafter.height / imgorigin.height : imgafter.width / imgorigin.width;
    }
 
    function getWrapPaddings(image, imagewrapper) {
        return {
            ‘padding-top‘: (imagewrapper.height - image.matrix.dh) / 2,
            ‘padding-left‘: (imagewrapper.width - image.matrix.dw) / 2
        };
    }
 
    function getWrapPaddingsFull(image, imagewrapper) {
        return {
            ‘padding-top‘: (imagewrapper.height - image.matrix.dh) / 2,
            ‘padding-bottom‘: (imagewrapper.height - image.matrix.dh) / 2,
            ‘padding-left‘: (imagewrapper.width - image.matrix.dw) / 2,
            ‘padding-right‘: (imagewrapper.width - image.matrix.dw) / 2
        };
    }
 
    /**
     * 使用jcrop裁剪
     * @param {type} file
     * @param {type} $imgwrap 要建材的包裹img对象
     * @param {type} callback 回调 @param domimg , jcrop c object , image.matrix
     * @returns {undefined}
     */
    function getCropArea(file, $imgwrap, callback) {
        FileAPI.getInfo(file, function(err, info) {
            var image = FileAPI.Image(file);
            ratio = getRatio(info, imgos);
            image.matrix.dw = info.width * ratio;
            image.matrix.dh = info.height * ratio;
            cropMain.css(getWrapPaddingsFull(image, imgos));
 
            image.get(function(error, img1) {
                if (error) {
                    alert("图片读取出错!");
                    // return;
                }
 
                $imgwrap.empty();
                $(‘<div />‘).appendTo($imgwrap)
                        .html($(img1))
                        .Jcrop({
                            onSelect: function(c) {
                                image.matrix.sx = c.x / ratio;
                                image.matrix.sy = c.y / ratio;
                                image.matrix.sw = c.w / ratio;
                                image.matrix.sh = c.h / ratio;
                                var r = c.h / c.w;
                                image.matrix.dw = imgPreviewWidth;
                                image.matrix.dh = imgPreviewWidth * r;
                                image.get(function(error, domimg) {
                                    //  $(‘<div class="padding-top-10"></div>‘).appendTo(imageLists).html($(domimg));
                                    callback.call(domimg, c, image.matrix);
                                    file.cropMatrix = $.extend(true, {}, image.matrix);
                                    file.cropMatrix.dw = 0;
                                    file.cropMatrix.dh = 0;
                                });
 
                            }
                        });//end jcrop
            }); //end get
 
        });  //end getInfo
    }
 
    /**
     * 生成居中的图像
     * @param {FileAPI.image} fileapi的 file 对象
     * @param  {width: *, height: *} 要生成的宽和高
     * @param {function} callback回调 @param $imgobj
     * @returns {undefined}  异步方法,不返回值
     */
    function getCenterImage(file, imgtoList, callback) {
        var $imagewrap;
        FileAPI.getInfo(file, function(err, info) {
 
            var r = getRatio(info, imgtoList);
            var img = FileAPI.Image(file);
 
            img.matrix.dw = info.width * r;
            img.matrix.dh = info.height * r;
 
            img.get(function(error, domimg) {
                if (error) {
                    alert("图片读取出错!");
                    return;
                }
                // $imagewrap = $(‘<div />‘).css( getWrapPaddingsFull(img,imgtoList)).append($(domimg));
                $imagewrap = $(‘<div />‘).append($(domimg).css({
                    ‘width‘: img.matrix.dw,
                    ‘height‘: img.matrix.dh,
                    ‘display‘: ‘block‘
                })).css(getWrapPaddingsFull(img, imgtoList));
                callback($imagewrap);
            });
 
        });
    }
    /**
     * 生成居中的img图像 ,注意设置传入img的matrix对象 sw和sh值
     * @param {FileAPI.image} fileapi的image对象
     * @param  {width: *, height: *} 要生成的宽和高
     * @param {function} callback回调 @param $imgobj
     * @returns {undefined} 异步方法,不返回值
     */
    function getCenterCropImage(img, imgtoList, callback) {
        var $imagewrap;
        var info = {width: img.matrix.sw, height: img.matrix.sh};
        var r = getRatio(info, imgtoList);
        //var img = FileAPI.Image(file);
 
        img.matrix.dw = info.width * r;
        img.matrix.dh = info.height * r;
 
        img.get(function(error, domimg) {
            if (error) {
                alert("图片读取出错!");
                return;
            }
            // $imagewrap = $(‘<div />‘).css( getWrapPaddingsFull(img,imgtoList)).append($(domimg));
            $imagewrap = $(‘<div />‘).append($(domimg).css({
                ‘width‘: img.matrix.dw,
                ‘height‘: img.matrix.dh,
                ‘display‘: ‘block‘
            })).css(getWrapPaddingsFull(img, imgtoList));
            callback($imagewrap);
        });
 
    }
 
    /**
     * 生成原始img图像,有一层div包裹
     * @param {FileAPI.file}  fileapi的file对象
     * @param  {width: *, height: *}  imgtoList 要生成的宽和高
     * @param {function} callback回调 @param $imgobj
     * @returns {undefined} 异步方法,不返回值
     */
 
    function getDomImage(file, imgtoList, callback) {
        var $imagewrap;
        FileAPI.getInfo(file, function(err, info) {
            var r = getRatio(info, imgtoList);
            var img = FileAPI.Image(file);
 
            img.matrix.dw = info.width * r;
            img.matrix.dh = info.height * r;
 
            if (imgtoList.height === 0) {
                img.matrix.dw = imgtoList.width;
                img.matrix.dh = imgtoList.width * info.height / info.width;
            }
 
            if (imgtoList.width === 0) {
                img.matrix.dw = imgtoList.height;
                img.matrix.dh = imgtoList.height * info.width / info.height;
            }
 
            img.get(function(error, domimg) {
                if (error) {
                    alert("图片读取出错!");
                    return;
                }
                $imagewrap = $(‘<div />‘).append($(domimg));
                callback($imagewrap);
            });
 
        });
    }
 
    function recurseIterate(array, callback) {
        recurseIterate.i = recurseIterate.i || 0;
        if (i >= array.length) {
            return;
        }
        callback();
 
    }
 
    return {
        getCropArea: getCropArea,
        getCenterImage: getCenterImage,
        config: config,
        getDomImage: getDomImage,
        getCenterCropImage: getCenterCropImage
 
    };
};

 

 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
var files = [];
//源文件名称 全局变量
var filesrc;
seajs.use([ ‘arale/dialog/1.2.3/dialog‘ ,  ‘arale/dialog/1.2.3/dialog.css‘], function( Dialog) {
    //seajs.use(‘extCss/designer/uploadtpl.css‘);
    var cropUtil = new ImgCropUtil({
        imgos: {width: 360, height: 360},
        cropMain: $(‘.crop-main-imgwrap‘),
        imgPreviewWidth: 65
    });
 
    var imageLists = $(‘.crop-aside-imglists‘);
    var imgtoPreview = {width: 65, height: 0}; //编辑页面图像大小,锁定宽度为65
    var editIndex = 0; //编辑页面当前图片号
 
    var imglistTemplate = $(‘#img-list-template‘).html();
    var imglistbox = $(‘#imglistbox‘); //主页面图像预览列表
    var imgtoList = {width: 180, height: 160}; //主页面图像预览大小
 
    var pixelwidth = $(‘.edit-wrap-btn-group .pixel-width‘);
    var pixelheight = $(‘.edit-wrap-btn-group .pixel-height‘);
 
    var dialog = new Dialog({
        content: $(‘#edit-wrap‘)
    });
 
    FileAPI.event.on($(‘#choose‘).get(0), ‘change‘, function(evt) {
        var filenew = FileAPI.getFiles(evt);
//        if ((filenew.length + files.length) > 6) {
//            confirmBox.show("图片最多上传6个");
//            return;
//        }
 
        FileAPI.filterFiles(filenew, function(file, info) {
            if (/^image/.test(file.type)  ) {
                return true;
            }
            else {
                confirmBox.show("图片格式必须为 jpg/gif/png");
                return false;
            }
 
        }, function(list, other) {
            if (list.length) {
                files = files.concat(list);
 
                function recurse() {
                    recurse.i = recurse.i || 0;
                    if (recurse.i >= list.length) {
                        $(‘#imglistbox .chk:first‘).addClass(‘checked‘);
                        return;
                    }
                    cropUtil.getCenterImage(list[recurse.i], imgtoList, function($imgout) {
                        $(imglistTemplate).find(‘.figure-upload-img‘).html($imgout).end().appendTo(imglistbox);
                        recurse.i++;
                        recurse(list[recurse.i]);
                    });
                }
                recurse();  //单线递归加载图片
            }
        });
    });
 
    //删除
    imglistbox.on(‘click‘, ‘.delete-figure‘, function(e) {
        var figureupload = $(this).closest(‘.figure-upload‘);
        var index = $(‘#imglistbox .figure-upload‘).index(figureupload);
 
        confirmBox.confirm(‘您确定要删除该模板?‘, ‘请确认‘, function() {
        }, {
            onConfirm: function() {
                var that = this;
                this.set(‘message‘, ‘执行中,请稍候...‘);
                // $(obj).parents(‘.figure-upload‘).remove();
                files.splice(index, 1);
                $(‘#imglistbox .figure-upload‘).eq(index).remove();
 
                that.hide();
            },
            closeTpl: ‘ב, // 关闭的按钮设置为空
            width: 300  // 宽度设置为 300 px
        });
 
    });
 
    //编辑
    imglistbox.on(‘click‘, ‘.edit-figure‘, function(e) {
        e.preventDefault();
        dialog.show();
        pixelwidth.text("");
        pixelheight.text("");
        var figureupload = $(this).closest(‘.figure-upload‘);
 
        //设置当前编辑index
        editIndex = $(‘#imglistbox .figure-upload‘).index(figureupload);
 
        imageLists.empty();
        crop(editIndex);
 
        recurse(); //单线递归加载图片
        function recurse() {
            recurse.i = recurse.i || 0;
            if (recurse.i >= files.length) {
                recurse.i = 0;
                return;
            }
            cropUtil.getDomImage(files[recurse.i], imgtoPreview, function($imgout) {
                $imgout.addClass(‘img-preview‘).css({
                    ‘margin-bottom‘: ‘10px‘,
                    ‘cursor‘: ‘pointer‘
                }).appendTo(imageLists);
                recurse.i++;
                recurse(files[recurse.i]);
            });
        }
 
        //点击切换编辑图片
        imageLists.on(‘click‘, ‘.img-preview‘, function() {
            editIndex = $(this).index(‘.img-preview‘);
            crop(editIndex);
        });
 
        function crop(index) {
            cropUtil.getCropArea(files[index], cropUtil.config.cropMain, function(c, imgmatrix) {
                imageLists.children().eq(index).html($(this));
                files[index].edit = true;
                pixelwidth.text(Math.floor(imgmatrix.sw) + ‘px‘);
                pixelheight.text(Math.floor(imgmatrix.sh) + ‘px‘);
            });
        }
 
    });//end 编辑
 
    //保存
    $(‘#edit-comfirm-btns .ui-button-lorange‘).on(‘click‘, function() {
        //应用修改到主页面
        $.each(files, function(index, file) {
            if (file.edit) {
                var image = FileAPI.Image(files[index]);
                image.matrix = files[index].cropMatrix;
                cropUtil.getCenterCropImage(image, imgtoList, function($imgout) {
                    $(‘#imglistbox‘).children(‘.figure-upload‘).eq(index).find(‘.figure-upload-img‘).html($imgout);
                    file.outputMatrix = image.matrix;
                    file.outputMatrix.dh = 0;
                    file.outputMatrix.dw = 0;
                });
            }
        });
        dialog.hide();
    });
 
    //关闭编辑页面时清空edit属性
    dialog.after(‘hide‘, function() {
        $.each(files, function(index, file) {
            file.edit = false;
        });
 
        imageLists.css({
            ‘margin-top‘: ‘0px‘
        });
    });
 
    $(‘#edit-comfirm-btns .ui-button-grey‘).on(‘click‘, function() {
        dialog.hide();
 
    });
    //点击滑动事件
    $(‘.crop-aside-slidedown‘).on(‘click‘, function() {
        if (imageLists.children().length <= 1) {
            return;
        }
        var margintop = parseInt(imageLists.css(‘margin-top‘).replace("px", "")) || 0;
        margintop = margintop - 65;
 
        if (-margintop > ($(‘.crop-aside-imglists‘).height() - 65)) {
            return;
        }
        imageLists.animate({
            ‘margin-top‘: margintop + ‘px‘
        });
    });
 
    //设为封面 编辑页面
    $(‘#set-front‘).on(‘click‘, function() {
        $(‘#imglistbox .chk‘).removeClass(‘checked‘);
        $(‘#imglistbox .chk‘).eq(editIndex).addClass(‘checked‘);
 
    });
 
    //设为封面 主页面
 
    imglistbox.on(‘click‘, ‘.chk‘, function() {
        imglistbox.find(‘.chk‘).removeClass(‘checked‘);
        $(this).addClass(‘checked‘);
    });
 
    // 重新上传
    FileAPI.event.on($(‘#reload-img‘).get(0), ‘change‘, function(evt) {
 
        var filenew = FileAPI.getFiles(evt);
        FileAPI.filterFiles(filenew, function(file, info) {
            if (/^image/.test(file.type) && file.size < 5 * FileAPI.MB) {
                return true;
            }
            else {
                confirmBox.show("图片大小不能超过5m,并且格式必须为 jpg/gif/png");
                return false;
            }
        }, function(list, other) {
            if (list.length) {
                files[editIndex] = list[0];
                //替换当前裁剪图片
                cropUtil.getCropArea(list[0], cropUtil.config.cropMain, function(c, imgmatrix) {
                    imageLists.children().eq(editIndex).html($(this));
                    files[editIndex].edit = true;
                    pixelwidth.text(Math.floor(imgmatrix.sw) + ‘px‘);
                    pixelheight.text(Math.floor(imgmatrix.sh) + ‘px‘);
                });
                //替换主页面列表图片
                cropUtil.getCenterImage(list[0], imgtoList, function($imgout) {
                    $(‘#imglistbox‘).children(‘.figure-upload‘).eq(editIndex).find(‘.figure-upload-img‘).html($imgout);
                });
                //替换裁剪列表图片
                cropUtil.getDomImage(list[0], imgtoPreview, function($imgout) {
                    $(‘.crop-aside-imglists‘).children().eq(editIndex).html($imgout);
                });
            }
        });
    }); //end 重新上传
 
});