html上传图片后压缩图片,图片预览,获取压缩后的Base64

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="file" onchange="loadImg(this)">
    <canvas style="width: 200px; height: 200px;"></canvas>
    <img src="" alt="" id="imgs">
    <script>
        //  上传图片
        function loadImg(me) {
            
            let img = document.querySelector('img');
            let cvs = document.querySelector('canvas');
            let file = me.files[0];    //  获取到文件对象
            //  上传的图片大于 500KB 时才压缩
            if (file && (file.size / 1024 > 150)) {
                let reader = new FileReader();
                reader.readAsDataURL(file);     //  转成 base64 编码
                reader.onload = function (e) {
                    let naturalBase64 = e.target.result;    //  获取 base64 编码,这是原图的
                    img.src = naturalBase64;
                    img.onload = function () {
                        let ratio = img.naturalWidth / img.naturalHeight; //  获取原图比例,为了等比压缩
                        cvs.width = 400;
                        cvs.height = cvs.width / ratio;
                        let ctx = cvs.getContext('2d');
                        ctx.drawImage(img, 0, 0, cvs.width, cvs.height);    //  画在 canvas 上
                        // 压缩后新图的 base64
                        let zipBase64 = cvs.toDataURL('image/jpeg',0.7);//0.7代表图片质量
                     	console.log(zipBase64)
                    }
                }
            }
        }
    </script>
</body>

</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值