图片压缩

基于vue的图片上传压缩

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>基于vue的图片上传压缩</title></head>
<body>
<input class="hiddenInput" type="file" name="uploadFile" id="imageFile" accept="image/*" @change="uploadImg($event)"/>
</body>
</html>
<script>
    //图片压缩//
    function photoCompress(file) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.onload = function () {
                img.src = e.target.result;
            }

            reader.onerror = function (e) {
                reject(e);
            }

            reader.readAsDataURL(file);
            img.onload = function () {
                resolve(img);
            }
            img.onerror = function () {
                reject(e);
            }
        })
    }

    //canvas绘制图片//
    function canvasDataURL(img, type, mx, mh) {
        return new Promise((resolve, reject) => {
            let canvas = document.createElement('canvas');
            let context = canvas.getContext('2d');
            let ctx = canvas.getContext('2d');
            let quality = 0.7// 默认图片质量为0.7//
            // 创建属性节点
            let anw = document.createAttribute('width')
            anw.nodeValue = mx
            let anh = document.createAttribute('height')
            anh.nodeValue = mh
            canvas.setAttributeNode(anw)
            canvas.setAttributeNode(anh)
            ctx.drawImage(img, 0, 0, mx, mh);
            // 图像质量       //         //
            if (file.size > 300 * 1024) {
                quality = 0.3
            }
            // quality值越小,所绘制出的图像越模糊//
            let base64 = canvas.toDataURL('image/jpeg', quality)
            resolve(base64)
        })
    }

    function convertBase64UrlToBlob(urlData) {
        let arr = urlData.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], {type: mime})
    }

    //上传//
    async function upload(file) {
        const img = await photoCompress(file);
        const blob = await canvasDataURL(img, file.type, 1000, 1000);
    }

    function convertBase64UrlToBlob(urlData) {
        let arr = urlData.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], {type: mime})
    }

    function canvasDataURL(path, file, callback) {
        let img = new Image()
        img.src = path
        img.onload = function () {
            const {width: originWidth, height: originHeight} = img;
            // 默认按比例压缩
            let w = img.width
            let h = img.height
            let quality = 0.7
            // 默认图片质量为0.7
            // 生成canvas
            let canvas = document.createElement('canvas')
            let ctx = canvas.getContext('2d')
            // 创建属性节点
            let anw = document.createAttribute('width')
            anw.nodeValue = w
            let anh = document.createAttribute('height')
            anh.nodeValue = h
            canvas.setAttributeNode(anw)
            canvas.setAttributeNode(anh)
            ctx.drawImage(img, 0, 0, w, h)
            // 图像质量
            console.log(`压缩之前的大小:${file.size / 1024}kb`)
            if (file.size > 300 * 1024) {
                quality = 0.3
            }
            // quality值越小,所绘制出的图像越模糊
            let base64 = canvas.toDataURL('image/jpeg', quality)
            callback(base64)
        }
    }

    function photoCompress(file, objDiv) {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function () {
            let result = this.result;
            let img = canvasDataURL(result, file, objDiv)
        }
    }

    document.getElementById("imageFile").addEventListener("change", function (e) {
        upload(e);
    })

    function upload(e) {
        const file = e.target.files[0];
        photoCompress(file, function (base64Codes) {
            let form = new FormData();
            let bl = convertBase64UrlToBlob(base64Codes);
            console.log(`压缩之后的大小:${bl.size / 1024}kb`)
        });
    }
</script>

 

上传文件压缩

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上传文件压缩</title></head>
<body>
<div>
    <h3>图片上传压缩</h3>
    <input type="file" id="file" placeholder="请上传图片" accept="image/*"/>
</div>
</body>
</html>
<script>
    document.getElementById("file").addEventListener("change", function (e) {
    console.log("压缩前", e.target.files[0].size);
    let result = e.target.files[0];
    opload(result);
})

function readImg(file) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        const reader = new FileReader();
        reader.onload = function (e) {
            img.src = e.target.result;
            console.log(e);
        }
        reader.onerror = function (e) {
            reject(e);
        }
        reader.readAsDataURL(file);
        img.onload = function () {
            resolve(img);
        }
        img.onerror = function () {
            reject(e);
        }
    })
}
//图片压缩
function compressImg(img, type, mx, mh) {
    return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        const {width: originWidth, height: originHeight} = img;
        // 最大尺寸限制
        const maxWidth = mx;
        const maxHeight = mh;
        // 目标尺寸
        let targetWidth = originWidth;
        let targetHeight = originHeight;
        if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > 1) {
                //  宽图片
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth))
            } else {
                // 高图片
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
        }
        canvas.width = targetWidth;
        canvas.height = targetHeight;
        context.clearRect(0, 0, targetWidth, targetHeight);
        // 图片绘制
        context.drawImage(img, 0, 0, targetWidth, targetHeight);
        canvas.toBlob(function (blob) {
            console.log(blob);
            resolve(blob);
        }, type || 'image/png')
    })
}

async function opload(file) {
    const img = await readImg(file);
    console.log(img);
    const blob = await compressImg(img, file.type, 1000, 1000);
    const formData = new FormData();
    console.log("压缩后", blob);
    formData.append("file", blob, `file_${Date.parse(new Date())}.jpg`);
}
</script>

 

vue

<template>
    <div>
        <input class="hiddenInput" type="file" name="uploadFile" id="imageFile" accept="image/*"
               @change="uploadImg($event)"/>
    </div>
</template>

<script>
    export default {
        data() {
            return {

            }
        },
        created() {

        },
        methods: {
            uploadImg(e) {
                const file = e.target.files[0];
                this.photoCompress(file, (base64Codes) => {
                    let form = new FormDate();
                    form.append("op;loadFile", b1, `file_${Date.parse(new Date())}.jpg`);
                    UploadImgInClaim(form).then((res) => {
                        if (res.status) {
                            let url = window.URL.createObjectURL(file);
                        }
                    }).catch((err) => {
                        console.log(err);
                    })
                })
            },
            //图片压缩
            photoCompress(file, objDiv) {
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function () {
                    let result = this.result;
                    this.canvasDataURL(result, file, objDiv);
                }
            },
            canvasDataURL(path, file, callback) {
                let img = new Image();
                img.src = path;
                img.onload = function () {
                    let _this = this;
                    //按比例默认缩放
                    let w = _this.width;
                    let h = _this.height;
                    let quality = 0.7;
                    //生成canvas
                    let canvas = document.createElement("canvas");
                    let ctx = canvas.getContext("2d");
                    //创建属性节点      // 创建属性节点
                    let anw = document.createAttribute('width')
                    anw.nodeValue = w
                    let anh = document.createAttribute('height')
                    anh.nodeValue = h
                    canvas.setAttributeNode(anw)
                    canvas.setAttributeNode(anh)
                    ctx.drawImage(_this, 0, 0, w, h)
                    // 图像质量
                    console.log(`压缩之前的大小:${file.size / 1024}kb`)
                    if (file.size > 300 * 1024) {
                        quality = 0.3
                    }
                    // quality值越小,所绘制出的图像越模糊
                    let base64 = canvas.toDataURL('image/jpeg', quality)
                    callback(base64)
                }
            },
            convertBase64UrlToBlob(urlData) {
                let arr = urlData.split(',')
                let mime = arr[0].match(/:(.*?);/)[1]
                let bstr = atob(arr[1])
                let n = bstr.length
                let u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new Blob([u8arr], {type: mime})
            }
        }
    }
</script>

<style>

</style>

 

上一篇:学院信息维护-查询学院信息03


下一篇:四大传值详解:属性传值,单例传值,代理传值,block传值