javascript - 在此基础上如何实现图片压缩上传?
迷茫
迷茫 2017-04-11 12:35:39
0
1
748

新手入门,实现了图片预览和上传,但是不懂压缩,在网上找了一段压缩函数,但是一直套不进去,请前辈指点,如何在现有html、js、php基础上加入压缩,谢谢o(∩_∩)o 。。。代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title></title>
        <script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
        <style>
            .LXXUploadPic{
                margin-left:10px;
                margin-top:10px;
            }
            .LXXUploadPic td{
                width:64px;
                height:64px;    
                background:#f3f3f3;
                position: relative;
                text-align:center;
            }

            input[type='file']{
                width: 100%;
                height: 100%;
                overflow: hidden;
                position:absolute;
                right:0;
                top:0;
                opacity: 0;
                cursor:pointer;
            }
            .displaynone{
                width:10px!important;
                background:url()!important;
            }
        </style>
    </head>
    <body id="top">        
        <form action="upload.php" method="post" enctype="multipart/form-data" id="formid">
                <p id="LXXUploadPic" LXXCol="3" LXXRow="1" LXXWidth="100" LXXHeight="100"></p>
                <input type="button" onclick="get();" class="queding" value="确定"/>                    
        </form>
        
        <script type="text/javascript">  
            function get(){                
                document.getElementById("formid").submit();
            } 
            
            //配置项
            var colNumber = 1;    //列数
            var rowNumber = 2;    //行数
            var width = 300;    //框高
            var height = 100;    //框宽

            /**
            根据配置项搭建UI
            */
            function makeUI(){
            //从html标签读取配置项
                var htmlColNumber = $('#LXXUploadPic').attr('LXXCol');
                var htmlRowNumber = $('#LXXUploadPic').attr('LXXRow');
                colNumber = htmlColNumber ? parseInt(htmlColNumber) : colNumber;
                rowNumber = htmlRowNumber ? parseInt(htmlRowNumber) : rowNumber;

                var htmlWidth = $('#LXXUploadPic').attr('LXXWidth');
                var htmlHeight = $('#LXXUploadPic').attr('LXXHeight');
                width = width ? parseInt(htmlWidth) : width;
                height = height ? parseInt(htmlHeight) : height;


                //开始搭建UI
                var html = "<table class='LXXUploadPic'>";

                for(var i = 0; i<rowNumber; i++){
                    html += "<tr>";
                    for(var j = 0; j<colNumber; j++){
                        html += "<td><input type='file' name='file[]' id=img"+j+" /></td>";
                        html += "<td class="+"displaynone"+"></td>";
                    }
                    html += "</tr>";
                }
                html += "</table>";

                $('#LXXUploadPic').html(html);
                //$('.LXXUploadPic tr td').css('width', width).css('height', height);
            }

            /**
            根据input[file]对象获取添加的图片url
            */
            function getObjectURL(file) {
                var url = null;
                if (window.createObjectURL != undefined) {
                    url = window.createObjectURL(file)
                } else if (window.URL != undefined) {
                    url = window.URL.createObjectURL(file)
                } else if (window.webkitURL != undefined) {
                    url = window.webkitURL.createObjectURL(file)
                }
                return url
            };

            /**
            选中图片将图片显示出来
            */
            function changeToShow(){
                $('input[type="file"]').change(function(){
                    //根据input[file]对象获取添加的图片url
                    var src = getObjectURL(this.files[0]);
                    $(this).parent().css('background', 'url(' + src + ') no-repeat center center').css('background-size', '100% 100%');
                });
            }


            $(document).ready(function(){
                //根据配置项搭建UI
                makeUI();
                //选中图片将图片显示出来
                changeToShow();
            });
        </script>        
    </body>
</html>

php接收:


    <?php
//打印三维数组$_FILES中的内容,查看一下存储上传文件的结构
print_r($_FILES);
echo "<br/>";
echo "<br/>";
echo "<br/>";
var_dump($_POST);
echo "<br/>";
echo "<br/>";
echo "<br/>";
$dest_folder   =  "images/";
if(!file_exists($dest_folder)){      
    if(mkdir($dest_folder)){       
    }else{
        echo"创建文件夹失败<br/>";
    }
}  

foreach ($_FILES["file"]["error"] as $key => $error ){  
    if ($error == UPLOAD_ERR_OK) 
    {        
        $tmp_name = $_FILES["file"]["tmp_name"][$key];     
        $name    = time().$key.$_FILES["file"]["name"][$key];        
        $uploadfile = $dest_folder.$name; 
        //$filepath="/images/";
        //$filepath=$filepath.$uploadfile;        
        move_uploaded_file($tmp_name, $uploadfile); 

        

        $php_self = $_SERVER['PHP_SELF'];
        $php_dir = dirname($php_self);
        //$url = 'http://'.$_SERVER['HTTP_HOST'].$php_dir.'/'.$uploadfile;

        $arr = array(
            'id' => $key,
            //'url' => $url
            'url' => $name
        );
        echo json_encode($arr);

        
    }
  }
?>

网上找的压缩函数:

//    使用canvas对大图片进行压缩
function compress(img) {
    var initSize = img.src.length;
    var width = img.width;
    var height = img.height;

    //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
    var ratio;
    if ((ratio = width * height / 4000000) > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
    } else {
        ratio = 1;
    }

    canvas.width = width;
    canvas.height = height;

    //        铺底色
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    //如果图片像素大于100万则使用瓦片绘制
    var count;
    if ((count = width * height / 1000000) > 1) {
        count = ~~ (Math.sqrt(count) + 1); //计算要分成多少块瓦片
        //            计算每块瓦片的宽和高
        var nw = ~~ (width / count);
        var nh = ~~ (height / count);

        tCanvas.width = nw;
        tCanvas.height = nh;

        for (var i = 0; i < count; i++) {
            for (var j = 0; j < count; j++) {
                tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);

                ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
            }
        }
    } else {
        ctx.drawImage(img, 0, 0, width, height);
    }

    //进行最小压缩
    var ndata = canvas.toDataURL('image/jpeg', 0.1);

    console.log('压缩前:' + initSize);
    console.log('压缩后:' + ndata.length);
    console.log('压缩率:' + ~~ (100 * (initSize - ndata.length) / initSize) + "%");

    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;

    return ndata;
}
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
大家讲道理

这也叫压缩……这不就是把图片缩小了嘛。

要上传的话,去学习一下表单的操作,以及 Ajax 你也应该用得上。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!