前端js圖片壓縮


今天被問到前端怎么圖片壓縮,然后就一頓的查資源,終於知道前端怎么壓縮圖片。

關鍵:

FileReader()

toDataURL()

上面兩個是關鍵方法,是html5后出現的好東西。

就是把圖片轉換成Base64編碼,那樣就可以不用理圖片在哪了,

他就被你轉換成編碼了。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js壓縮圖片</title>
    <script src="jquery.js"></script>
</head>
<body>
    <input type="file" name="file" id="file">
    <div id="container"></div>
    
    <script>
    /*圖片地址
    https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E9%AB%98%E6%B8%85%E7%BE%8E%E5%A5%B3%20%E4%B8%9D%E8%A2%9C%E5%B7%A8%E4%B9%B3&step_word=&hs=0&pn=1&spn=0&di=57234189540&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=3589338782%2C536437810&os=3988412231%2C488396405&simid=3515890414%2C233897128&adpicid=0&lpn=0&ln=1389&fr=&fmq=1490709487003_R&fm=result&ic=0&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fwww.bz55.com%2Fuploads%2Fallimg%2F150416%2F139-1504161AK9.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bkzcc_z%26e3Bv54AzdH3F4jtgektzitAzdH3F8l9c9_z%26e3Bip4s&gsm=0&rpstart=0&rpnum=0
    */
    $(function(){
        $("#file").on("change",function(){
            var file=this.files[0];
            photoCompress(file,50,$("#container")[0])

        });
    })


/*
三個參數
file:一個是文件(類型是圖片格式),
w:一個是文件壓縮的后寬度,寬度越小,字節越小
objDiv:一個是容器或者回調函數
photoCompress()
 */
    function photoCompress(file,w,objDiv){
        var ready=new FileReader();
            /*開始讀取指定的Blob對象或File對象中的內容. 當讀取操作完成時,readyState屬性的值會成為DONE,如果設置了onloadend事件處理程序,則調用之.同時,result屬性中將包含一個data: URL格式的字符串以表示所讀取文件的內容.*/
            ready.readAsDataURL(file);
            ready.onload=function(){
                var re=this.result;
                canvasDataURL(re,w,objDiv)
            }
    }
    function canvasDataURL(re,w,objDiv){
        var newImg=new Image();
        newImg.src=re;
        var imgWidth,imgHeight,offsetX=0,offsetY=0;
        newImg.onload=function(){
            var img=document.createElement("img");
            img.src=newImg.src;
            imgWidth=img.width;
            imgHeight=img.height;
            var canvas=document.createElement("canvas");
            canvas.width=w;
            canvas.height=w;
            var ctx=canvas.getContext("2d");
            ctx.clearRect(0,0,w,w);
            if(imgWidth>imgHeight){
                imgWidth=w*imgWidth/imgHeight;
                imgHeight=w;
                offsetX=-Math.round((imgWidth-w)/2);
            }else{
                imgHeight=w*imgHeight/imgWidth;
                imgWidth=w;
                offsetY=-Math.round((imgHeight-w)/2);
            }
            ctx.drawImage(img,offsetX,offsetY,imgWidth,imgHeight);
            var base64=canvas.toDataURL("image/jpeg",0.7);
            if(typeof objDiv == "object"){
                objDiv.appendChild(canvas);
            }else if(typeof objDiv=="function"){
                objDiv(base64);
            }
        }
        
    }

    </script>
</body>
</html>

直接調用這個方法:

photoCompress()
傳進參數就可以實現壓縮了,這是上傳圖片的。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js壓縮圖片</title>
    <script src="jquery.js"></script>
</head>
<body>
    <input type="file" name="file" id="file">
    <div id="container"></div>
    
    <script>
    /*跨域是無法做的*/
    $(function(){

        var newImg=new Image();
        newImg.src="./timg.jpg";
        newImg.onload=function(){
            var currentImg=document.createElement("img");
            currentImg.src=newImg.src;
            photoCompress(currentImg,50,$("#container")[0])
        }
    })


/*
三個參數
file:一個是文件(類型是圖片格式),
w:一個是文件壓縮的后寬度,寬度越小,字節越小
objDiv:一個是容器或者回調函數
photoCompress()
 */
    function photoCompress(file,w,objDiv){
        if(file.tagName.toLocaleLowerCase()=="img"){
            canvasDataURL(file.src,w,objDiv);
            return false;
        }
        var ready=new FileReader();
            /*開始讀取指定的Blob對象或File對象中的內容. 當讀取操作完成時,readyState屬性的值會成為DONE,如果設置了onloadend事件處理程序,則調用之.同時,result屬性中將包含一個data: URL格式的字符串以表示所讀取文件的內容.*/
            ready.readAsDataURL(file);
            ready.onload=function(){
                var re=this.result;
                canvasDataURL(re,w,objDiv)
            }
    }
    function canvasDataURL(re,w,objDiv){
        var newImg=new Image();
        newImg.src=re;
        var imgWidth,imgHeight,offsetX=0,offsetY=0;
        newImg.onload=function(){
            var img=document.createElement("img");
            img.src=newImg.src;
            imgWidth=img.width;
            imgHeight=img.height;
            var canvas=document.createElement("canvas");
            canvas.width=w;
            canvas.height=w;
            var ctx=canvas.getContext("2d");
            ctx.clearRect(0,0,w,w);
            if(imgWidth>imgHeight){
                imgWidth=w*imgWidth/imgHeight;
                imgHeight=w;
                offsetX=-Math.round((imgWidth-w)/2);
            }else{
                imgHeight=w*imgHeight/imgWidth;
                imgWidth=w;
                offsetY=-Math.round((imgHeight-w)/2);
            }
            ctx.drawImage(img,offsetX,offsetY,imgWidth,imgHeight);
            var base64=canvas.toDataURL("image/jpeg",0.7);
            if(typeof objDiv == "object"){
                objDiv.appendChild(canvas);
            }else if(typeof objDiv=="function"){
                objDiv(base64);
            }
        }
        
    }

    </script>
</body>
</html>

這是同域圖片壓縮。

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM