h5前端canvas压缩图片并异步上传图片 后台php处理压缩图片上传

h5前端canvas压缩图片并异步上传图片 后台php处理压缩图片上传

1、前端html代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>上传压缩图片并在页面展示</title>
 6 </head>
 7 <script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
 8 <body>
 9 <!--上传控件-->
10 <input type="file"  id="inputinput">
11 <img id="imageId" src="">
12 </body>
13 <script>
14     (function ($) {
15         $.extend({
16             //压缩图片,参数1:file对象,参数2:压缩比例
17             compress(file,scale) {
18                 return new Promise(function (resolve,reject) {
19                     let _scale=scale || 1;
20                     let cvs = document.createElement('canvas');
21                     let ctx = cvs.getContext('2d');
22                     let img = new window.Image();
23                     let imgType=file.type;
24                     img.src = URL.createObjectURL(file);
25                     img.onload=function () {
26                         if ( img.width > 600 || img.height > 600 ) {
27                             //当宽或高大于600时进行比例压缩
28                             cvs.width = img.width*_scale;
29                             cvs.height = img.height*_scale;
30                         } else {
31                             //此处可优化,如有兴趣可设置不进行1:1压缩
32                             cvs.width = img.width;
33                             cvs.height = img.height;
34                         }
35                         ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
36                         resolve(cvs.toDataURL(imgType));
37                     }
38                 });
39             }
40         });
41         $(function (){
42             $("#inputinput").change(function () {
43                 let files=$(this)[0].files[0];//获取files对象
44                 $.compress(files,0.1).then((url)=>{
45                 $.post('aaaaaa.php?act=upload',{base64:url},function(result){
46                     console.log(result['message'])
47                 },"json")
48             })
49             })
50         })
51         $(function (){
52             $("#inputinput").change(function () {
53                 let files=$(this)[0].files[0];//获取files对象
54                 $.compress(files,0.1).then((url)=>{
55                     $.post('test.php?act=act_upload',{base64:url},function(result){
56                     if( result['status']==200 ){
57                         //上传失败
58                         alert(result['message'])
59                     } else {
60                         //上传成功
61                         console.log(result['message'])
62                         $('#imageId').attr('src',result['message']);  //显示上传后的图片
63                     }
64                 },"json")
65             })
66             })
67         })
68     })(jQuery)
69 </script>
70 </html>

2、test.php   处理压缩图片并上传图片,其中从网上找的递归生成目录超级精简~

 1 /* 压缩图片 */
 2 if ($action == 'act_upload') {
 3     $up_ok = base64_upload($_POST['base64']);
 4     if ( $up_ok!== false && $_SESSION['user_id']>0) {
 5         $res['status'] = 0;
 6         $res['message'] = $up_ok;  //上传后的图片路径
 7         //图像此时可入库,代码省略
 8     } else {
 9         $res['status'] = 200;
10         $res['message'] = '您上传图片失败了,请重新尝试~';
11     }
12     echo json_encode($res);
13     exit;
14 }
15 
16 /**
17  * @description 处理base64的图片
18  * @param $post
19  *
20  */
21 function base64_upload($base64) {
22     $base64_image = str_replace(' ', '+', $base64);
23     //post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
24     if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
25         //匹配成功
26         if($result[2] == 'jpeg'){
27             $image_name = uniqid().'.jpg';  //可不用替换为jpg
28         }else{
29             $image_name = uniqid().'.'.$result[2];
30         }
31         $up_dir = './images/' . date("Ym") . "/";
32         if ( !is_dir($up_dir)) mkDirectory($up_dir);
33         $image_file = $up_dir . $image_name;
34         //服务器文件存储路径
35         if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
36             return substr($image_file,strpos($image_file,'./')+2);
37         }else{
38             return false;
39         }
40     }else{
41         return false;
42     }
43 }
44 /**
45  * @description 递归生成目录(超精简)
46  * @param $post
47  *
48  */
49 function mkDirectory( $dir ){
50     return  is_dir( $dir ) or mkDirectory(dirname( $dir )) and  mkdir( $dir , 0777);
51 }

猜你喜欢

转载自www.cnblogs.com/samgo/p/9184474.html