ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

图片压缩

2022-03-01 16:00:43  阅读:144  来源: 互联网

标签:function canvas img 压缩 let file new 图片


基于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>

 

标签:function,canvas,img,压缩,let,file,new,图片
来源: https://www.cnblogs.com/liufeiran/p/15950689.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有