JS图片压缩

JS图片压缩

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    


        <input type="file" id="file1"  onchange="selFile()"  />


   <img id="res" />




        <script>

            var maxWidth = 400;
            var maxHeight =400;
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');

            function selFile()
            {
                var file = null;
                var reader = new FileReader();
                var img = new Image();
                 
         
                //获取选中的文件
                file = file1.files[0];
                reader.readAsDataURL(file);
                
                reader.onload=function(e)
                {                                    
                    var base64 = reader.result.split(',')[1];
                    var dataUrl = 'data:image/png;base64,' + base64; 
                    img.src = dataUrl; 
                }



                img.onload = function () {

                    var originWidth = this.width;
                    var originHeight = this.height;

                    var targetWidth = originWidth;
                    var targetHeight = originHeight;

                    if (originWidth > maxWidth || originHeight > maxHeight) {
                        if (originWidth / originHeight > maxWidth / maxHeight) {
                            // 更宽,按照宽度限定尺寸
                            targetWidth = maxWidth;
                            targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                        } else {
                            targetHeight = maxHeight;
                            targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                        }
                    }



                    /////////////////// canvas


                    canvas.width = targetWidth;
                    canvas.height = targetHeight;

                    context.clearRect(0, 0, targetWidth, targetHeight);
                    context.drawImage(img, 0, 0, targetWidth, targetHeight);


                    var base64 = canvas.toDataURL('image/jpeg', 0.8);

                    res.src = base64;




                    /////////////////// canvas







                }


            }

        </script>



    </div>
    </form>
</body>
</html>

  

posted @ 2020-02-21 16:02  启明星工作室  阅读(323)  评论(0编辑  收藏  举报