码迷,mamicode.com
首页 > Web开发 > 详细

H5图片预览、压缩、上传

时间:2018-08-22 12:05:41      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:16px   asd   pen   title   方便   split   实现   分享图片   提示   

目标实现:

  1、选择图片, 前端预览效果

  2、图片大于1.2M的时候, 对图片进行压缩

  3、以表单的形式上传图片

  4、图片删除

   

预览效果图:

技术分享图片

 

代码说明:

1、input:file选择图片

<!-- html部分 -->
<ul id="preview" class="clear">
    <li class="fl">
        <img src="/images/audition/icon_upload.png">
        <input id="fileImage" type="file" name="file[]" multiple />
        <div class="num">0/4</div>
    </li>
</ul>

 

var imgId = 0;  //图片id标志, 方便删除预览图片

/* 选择图片 */
function choosePic() {
    $(‘#fileImage‘).change(function() {
        var files = this.files,
            len = $(‘#preview‘).find(‘.pic‘).length;
        if (len + files.length > 4) {
            showTip(‘最多只能上传4张图片哦~‘);
            return;
        }
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            if (file.type.indexOf("image") == 0) {
                if (file.size >= 1024 * 1024 * 3) {
                    showTip(‘图片大小过大,应小于3M‘);
                } else {
                    showPic(file); //图片预览
                }
            } else {
                showTip(‘文件"‘ + file.name + ‘"不是图片类型‘)
                break;
            }
        }
    });
}

 

2、图片预览(base64)

/* 渲染图片 */
function showPic(file) {
    var html = ‘‘,
        $wap = $(‘#preview‘),
        reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e) {
        var image_base64 = this.result;

        html = ‘<li class="fl pic" id="imgItem_‘ + imgId + ‘">‘ +
                    ‘<img src="‘ + image_base64 + ‘" >‘ +
                    ‘<i class="del-img"></i>‘ +
                ‘</li>‘;
        imgId++;        
        $wap.append(html);
        $(‘#fileImage‘).next().text($wap.find(‘.pic‘).length + ‘/4‘);    

        //图片压缩上传,大于1.2M压缩图片
        if (file.size / 1024 > 1024 * 1.2) {
            dealImage(image_base64, {
                quality: 0.5
            }, function(base64Codes) {
                var bl = processData(base64Codes, file.type);
                uploadPic(bl, imgId);
            });
        } else {
            uploadPic(file, imgId);
        }
    }
}

 

3、图片压缩

/**
 * 图片压缩(利用canvas)
 * @param  path     图片路径
 * @param  obj      压缩配置width,height,quality,不传则按比例压缩
 * @param  callback  回调函数
 */
function dealImage(path, obj, callback) {
    var img = new Image();
    img.src = path;
    img.onload = function() {
        var that = this;
        // 默认按比例压缩
        var w = that.width,
            h = that.height,
            scale = w / h;
        w = obj.width || w;
        h = obj.height || (w / scale);

        //生成canvas
        var canvas = document.createElement(‘canvas‘),
        ctx = canvas.getContext(‘2d‘);
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(that, 0, 0, w, h);

        // 默认图片质量为0.7
        var quality = 0.7;
        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
            quality = obj.quality;
        }

        // 回调函数返回base64的值
        var base64 = canvas.toDataURL(‘image/jpeg‘, quality);
        callback(base64);
    }
}

 

压缩后的文件是base64格式, 我们希望用file图片的形式上传

/* 将以base64的图片url数据转换为Blob */
function processData(dataUrl, type) {
    var binaryString = window.atob(dataUrl.split(‘,‘)[1]),
    arrayBuffer = new ArrayBuffer(binaryString.length),
    intArray = new Uint8Array(arrayBuffer);
    for (var i = 0, j = binaryString.length; i < j; i++) {
        intArray[i] = binaryString.charCodeAt(i);
    }

    var data = [intArray], blob;

    try {
        blob = new Blob(data);
    } catch (e) {
        window.BlobBuilder = window.BlobBuilder ||
            window.WebKitBlobBuilder ||
            window.MozBlobBuilder ||
            window.MSBlobBuilder;
        if (e.name === ‘TypeError‘ && window.BlobBuilder) {
            var builder = new BlobBuilder();
            builder.append(arrayBuffer);
            blob = builder.getBlob(type);
        } else {
            showTip(‘版本过低,不支持图片压缩上传‘);
        }
    }
    return blob;
}

 

4、图片上传

/* 上传图片 */
function uploadPic(file, id) {
    var formData = new FormData();
    formData.append(‘img‘, file);
    $.ajax({
        url: ‘/upload‘,
        type: ‘post‘,
        dataType: ‘json‘,
        data: formData,
        contentType: false,
        processData: false,           
        success: function(res){
            if(res.respCode == 1000) {
                $(‘#imgItem_‘ + id).find(‘.del-img‘).attr(‘data-src‘, res.data.src);                    
            }else {
                showTip(‘文件上传失败!‘); 
            }
        }
    });  
}

 

5、其他

function showTip(str) {
    //TODO:信息提示
    console.log(str);
}

 

/* 删除图片 */
function delPic() {
    var $wap = $(‘#preview‘);
    $wap.on(‘click‘, ‘.del-img‘, function() {
        //TODO:从数据库删除图片
        $(this).parent().remove();
        $(‘#fileImage‘).next().text($wap.find(‘.pic‘).length + ‘/4‘);    
    });
}

 

源码:

技术分享图片
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>前端图片预览压缩上传</title>
  6     <style>
  7         .clear::after {
  8           content: ‘‘;
  9           clear: both;
 10           display: block;
 11         }
 12         .fl {
 13             float: left;
 14         }
 15         .list-img li {
 16             position: relative;
 17             margin-right: 10px;
 18             list-style: none;
 19         }
 20         .list-img img {
 21             display: inline-block;
 22             width: 50px;
 23             height:50px;    
 24         }
 25         .list-img input {
 26             position: absolute;
 27             top: 0;
 28             z-index: 10;
 29             width: 50px;
 30             height:50px;
 31             opacity: 0;    
 32         }
 33         .list-img i {
 34             position: absolute;
 35             top: 0;
 36             right: 0;
 37             width: 15px;
 38             height: 15px;
 39             background: url(../images/icon_del.png) no-repeat center;
 40             background-size: 100%;
 41         }
 42         .list-img .num {
 43             position: absolute;
 44             left: 0;
 45             bottom: 0;
 46             width: 100%;
 47             text-align: center;
 48             color: #999;
 49             font-size: 12px;    
 50         }
 51     </style>
 52 </head>
 53 <body>
 54     <div class="list-img">
 55         <ul id="preview" class="clear">
 56             <li class="fl">
 57                 <img src="/images/icon_upload.png">
 58                 <input id="fileImage" type="file" name="file[]" multiple />
 59                 <div class="num">0/4</div>
 60             </li>
 61         </ul>
 62     </div>    
 63 
 64     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
 65     <script>
 66         var pageCtrl = {
 67             imgId : 0, //图片id标志, 方便删除预览图片
 68             maxNum : 4, //最多上传图片张数
 69 
 70             /* 选择图片 */
 71             _choosePic : function() {
 72                 var _self = this;
 73                 $(#fileImage).change(function() {
 74                     var files = this.files,
 75                         len = $(#preview).find(.pic).length;
 76                     if (len + files.length > _self.maxNum) {
 77                         _self._showTip(最多只能上传 + _self.maxNum + 张图片哦~);
 78                         return;
 79                     }
 80                     for (var i = 0; i < files.length; i++) {
 81                         var file = files[i];
 82                         if (file.type.indexOf("image") == 0) {
 83                             if (file.size >= 1024 * 1024 * 3) {
 84                                 _self._showTip(图片大小过大,应小于3M);
 85                             } else {
 86                                 _self._showPic(file); //图片预览
 87                             }
 88                         } else {
 89                             _self._showTip(文件" + file.name + "不是图片类型)
 90                             break;
 91                         }
 92                     }
 93                 });
 94             },
 95 
 96             /* 渲染图片 */
 97             _showPic : function(file) {
 98                 var _self = this,
 99                     html = ‘‘,
100                     $wap = $(#preview),
101                     reader = new FileReader();
102                 reader.readAsDataURL(file);
103                 reader.onload = function(e) {
104                     var image_base64 = this.result,
105                     imgId = _self.imgId;
106 
107                     html = <li class="fl pic" id="imgItem_ + imgId + "> +
108                                 <img src=" + image_base64 + " > +
109                                 <i class="del-img"></i> +
110                             </li>;
111                     imgId++;        
112                     $wap.append(html);
113                     $(#fileImage).next().text($wap.find(.pic).length + / + _self.maxNum);    
114 
115                     //图片压缩上传,大于1.2M压缩图片
116                     if (file.size / 1024 > 1024 * 1.2) {
117                         _self._dealImage(image_base64, {
118                             quality: 0.5
119                         }, function(base64Codes) {
120                             var bl = _self._processData(base64Codes, file.type);
121                             _self._uploadPic(bl, imgId);
122                         });
123                     } else {
124                         _self._uploadPic(file, imgId);
125                     }
126                 }
127             },
128 
129 
130             /**
131              * 图片压缩(利用canvas)
132              * @param  path     图片路径
133              * @param  obj      压缩配置width,height,quality,不传则按比例压缩
134              * @param  callback  回调函数
135              */
136             _dealImage : function(path, obj, callback) {
137                 var img = new Image();
138                 img.src = path;
139                 img.onload = function() {
140                     var that = this;
141                     // 默认按比例压缩
142                     var w = that.width,
143                         h = that.height,
144                         scale = w / h;
145                     w = obj.width || w;
146                     h = obj.height || (w / scale);
147 
148                     //生成canvas
149                     var canvas = document.createElement(canvas),
150                     ctx = canvas.getContext(2d);
151                     canvas.width = w;
152                     canvas.height = h;
153                     ctx.drawImage(that, 0, 0, w, h);
154 
155                     // 默认图片质量为0.7
156                     var quality = 0.7;
157                     if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
158                         quality = obj.quality;
159                     }
160 
161                     // 回调函数返回base64的值
162                     var base64 = canvas.toDataURL(image/jpeg, quality);
163                     callback(base64);
164                 }
165             },
166 
167             /* 将以base64的图片url数据转换为Blob */
168             _processData : function(dataUrl, type) {
169                 var binaryString = window.atob(dataUrl.split(,)[1]),
170                 arrayBuffer = new ArrayBuffer(binaryString.length),
171                 intArray = new Uint8Array(arrayBuffer);
172                 for (var i = 0, j = binaryString.length; i < j; i++) {
173                     intArray[i] = binaryString.charCodeAt(i);
174                 }
175 
176                 var data = [intArray], blob;
177 
178                 try {
179                     blob = new Blob(data);
180                 } catch (e) {
181                     window.BlobBuilder = window.BlobBuilder ||
182                         window.WebKitBlobBuilder ||
183                         window.MozBlobBuilder ||
184                         window.MSBlobBuilder;
185                     if (e.name === TypeError && window.BlobBuilder) {
186                         var builder = new BlobBuilder();
187                         builder.append(arrayBuffer);
188                         blob = builder.getBlob(type);
189                     } else {
190                         _showTip(版本过低,不支持图片压缩上传);
191                     }
192                 }
193                 return blob;
194             },
195 
196             /* 上传图片 */
197             _uploadPic : function(file, id) {
198                 var _self = this,
199                 formData = new FormData();
200                 formData.append(img, file);
201                 $.ajax({
202                     url: /upload,
203                     type: post,
204                     dataType: json,
205                     data: formData,
206                     contentType: false,
207                     processData: false,           
208                     success: function(res){
209                         if(res.respCode == 1000) {
210                             $(#imgItem_ + id).find(.del-img).attr(data-src, res.data.src);                    
211                         }else {
212                             _self._showTip(文件上传失败!); 
213                         }
214                     }
215                 });  
216             },
217 
218             /* 删除图片 */
219             _delPic : function() {
220                 var _self = this,
221                 $wap = $(#preview);
222                 $wap.on(click, .del-img, function() {
223                     //TODO:从数据库删除图片
224                     $(this).parent().remove();
225                     $(#fileImage).next().text($wap.find(.pic).length + / + _self.maxNum);    
226                 });
227             },
228 
229             _showTip : function(str) {
230                 //TODO信息提示
231                 console.log(str);
232             },
233 
234             init: function() {
235                 this._choosePic();
236                 this._delPic();        
237             }
238         };
239 
240         $(function() {
241             pageCtrl.init();
242         });
243     </script>
244 </body>
245 </html>
完整代码

 

参考文章:

https://www.cnblogs.com/007sx/p/7583202.html

 

H5图片预览、压缩、上传

标签:16px   asd   pen   title   方便   split   实现   分享图片   提示   

原文地址:https://www.cnblogs.com/ww03/p/9507039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!