首页 > 其他分享 >前端图片最优化压缩方案

前端图片最优化压缩方案

时间:2023-12-08 15:13:00浏览次数:24  
标签:1024 const file targetHeight originHeight 压缩 最优化 image 前端

            function compressImg(file, quality) {
                var qualitys = 0.52
                if (parseInt((file.size / 1024).toFixed(2)) < 1024) {
                    qualitys = 0.85
                }
                if (5 * 1024 < parseInt((file.size / 1024).toFixed(2))) {
                    qualitys = 0.92
                }
                if (quality) {
                    qualitys = quality
                }
                if (file[0]) {
                    return Promise.all(Array.from(file).map(e => compressImg(e,
                        qualitys))) // 如果是 file 数组返回 Promise 数组
                } else {
                    return new Promise((resolve) => {
              
                        if ((file.size / 1024).toFixed(2) < 300) {
                            resolve({
                                file: file
                            })
                        } else {
                            const reader = new FileReader() // 创建 FileReader
                            reader.onload = ({
                                target: {
                                    result: src
                                }
                            }) => {
                                const image = new Image() // 创建 img 元素
                                image.onload = async () => {
                                    const canvas = document.createElement('canvas') // 创建 canvas 元素
                                    const context = canvas.getContext('2d')
                                    var targetWidth = image.width
                                    var targetHeight = image.height
                                    var originWidth = image.width
                                    var originHeight = image.height
                                    if (1 * 1024 <= parseInt((file.size / 1024).toFixed(2)) && parseInt((file.size / 1024).toFixed(2)) <= 10 * 1024) {
                                        var maxWidth = 1600
                                        var maxHeight = 1600
                                        targetWidth = originWidth
                                        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))
                                            }
                                        }
                                    }
                                    if (10 * 1024 <= parseInt((file.size / 1024).toFixed(2)) && parseInt((file.size / 1024).toFixed(2)) <= 20 * 1024) {
                                        maxWidth = 1400
                                        maxHeight = 1400
                                        targetWidth = originWidth
                                        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.width = targetWidth
                                    canvas.height = targetHeight
                                    context.clearRect(0, 0, targetWidth, targetHeight)
                                    context.drawImage(image, 0, 0, targetWidth, targetHeight) // 绘制 canvas
                                    const canvasURL = canvas.toDataURL('image/jpeg', qualitys)
                                    const buffer = atob(canvasURL.split(',')[1])
                                    let length = buffer.length
                                    const bufferArray = new Uint8Array(new ArrayBuffer(length))
                                    while (length--) {
                                        bufferArray[length] = buffer.charCodeAt(length)
                                    }
                                    const miniFile = new File([bufferArray], file.name, {
                                        type: 'image/jpeg'
                                    })
                                    resolve({
                                        file: miniFile,
                                        origin: file,
                                        beforeSrc: src,
                                        afterSrc: canvasURL,
                                        beforeKB: Number((file.size / 1024).toFixed(2)),
                                        afterKB: Number((miniFile.size / 1024).toFixed(2))
                                    })
                                }
                                image.src = src
                            }
                            reader.readAsDataURL(file)
                        }
                    })
                }
            }

 

标签:1024,const,file,targetHeight,originHeight,压缩,最优化,image,前端
From: https://www.cnblogs.com/wzf-Learning/p/17887203.html

相关文章

  • JavaWeb - Day03 - Ajax、前端工程化、Element
    01.Ajax-介绍Ajax概念:AsynchronousJavaScriptAndXML,异步的JavaScript和XML。作用:数据交换:通过Ajax可以给服务器发送请求,并获取服务器响应的数据。异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用的校验等等......
  • vue-django 前端bootstrap配置
    2、前端引入bootstrap下载bootstrap源码,放在vue中的src目录中https://v5.bootcss.com/docs/getting-started/download/https://getbootstrap.net/docs/getting-started/introduction/在vue根目录修改main.jsimport{createApp}from'vue'importAppfrom'./App.vue'im......
  • 前端学习-JavaScript学习-js基础-API02
    学习视频:黑马程序员视频链接事件监听三要素:事件源、事件类型、事件处理程序随机点名案例<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"&......
  • Flask读取MySQL数据库中的图片并返回给前端的步骤?
    要在Flask中读取MySQL数据库中的图片并返回给前端,可以按照以下步骤进行操作:导入相关模块:在Flask应用程序文件中,首先导入必要的模块,包括Flask、MySQL驱动和一些辅助函数。fromflaskimportFlask,request,send_fileimportmysql.connector创建Flask应用程序实例:创建一个Flask应......
  • 前端问题记录:el-row和el-col出现排版错乱
    el-row和el-col出现排版错乱,如图使用场景:使用了el-row和col配合form使用,不操作时候页面排版是正确的,进行操作就会出现排版错乱。问题原因:因为el-row和el-col的中的span元素之和超过了24的时候,就会出现排版错乱解决方案:.el-row{display:flex;//设置布局flex-wrap:wrap;//......
  • 前端大屏适配几种方案
    一、方案一:rem+font-size动态设置HTML根字体大小和body字体大小,会使用到lib-flexible.js插件(functionflexible(window,document){vardocEl=document.documentElementvardpr=window.devicePixelRatio||1//adjustbodyfontsizefunctionsetBodyFontSize(......
  • 前端歌谣的刷题之路-第一百一十五题-根据包名 在指定空间中创建对象
     前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷本题目源自于牛客网微信公众号前端小歌谣题目......
  • 前端歌谣的刷题之路-第一百一十六题-数组去重
     前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷本题目源自于牛客网微信公众号前端小歌谣题目......
  • 前端歌谣的刷题之路-第一百一十七题-实现斐波那契数列
     前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷本题目源自于牛客网微信公众号前端小歌谣题目......
  • 前端优化之路:git commit 校验拦截
     【前言】 前面在git分支规范那篇文章里,介绍了commit提交规范,如下图 但是想要做到高效落地执行,就需要做些别的功课,先展示下成果图没错,对不符合规范的commit进行了拦截,符合才可以成功提交。   【前期准备】 需要了解githooks,它是git的钩子,就像vue拥有自己的......