您的位置:首页 > Web前端

前端input file 图片压缩

2019-05-05 21:22 120 查看
[code]<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>压缩图片</title>
</head>
<body>
    <img id="img" src="">
    <input id="file" type="file" onchange="compress()">
</body>
<script>

// 对图片进行压缩
function compress() { 
    let fileObj = document.getElementById('file').files[0] //上传文件的对象
    let reader = new FileReader()
    reader.readAsDataURL(fileObj)
    reader.onload = function(e) {
        let image = new Image() //新建一个img标签(还没嵌入DOM节点)
        image.src = e.target.result
        image.onload = function() {
            let canvas = document.createElement('canvas'), 
            context = canvas.getContext('2d'),
            imageWidth = image.width / 2,    //压缩后图片的大小
            imageHeight = image.height / 2,
            data = ''

            canvas.width = imageWidth
            canvas.height = imageHeight

            context.drawImage(image, 0, 0, imageWidth, imageHeight)
            data = canvas.toDataURL('image/jpeg')

            //压缩完成 
            document.getElementById('img').src = data
        }
    }
}
</script>
</html>

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: