美文网首页
vue uniapp 图片压缩

vue uniapp 图片压缩

作者: 吃肉肉不吃肉肉 | 来源:发表于2022-06-28 10:10 被阅读0次

压缩的图片质量是从0到1的范围取值,数值越小,压缩的图片越小,我用的默认值0.92
1.02M --> 229KB
2.53M --> 523KB
3.46M --> 723KB
如果图片过大(大于4.5M左右),压缩后仍然会大于1M,就会在压缩后的基础上再次进行压缩
4.73M --> 225KB

            // 选择图片
            chooseImgs() {
                let that = this
                uni.chooseImage({
                    count: 1, //默认9
                    success: res => {
                        this.images = res.tempFiles[0].path
                        console.log('压缩前', res.tempFiles[0])
                                                // 大于1M压缩
                        if (Math.ceil(res.tempFiles[0].size / 1024) > 1024) {
                            that.compress(res.tempFiles[0])
                        } else {
                            that.uploadImage(res.tempFiles[0])
                        }
                    }
                })
            },
            // 压缩图片
            compress(file, limit = 0.92, file_size = 50) {
                let _this = this
              return new Promise((resolve, reject) => {
                if (!file) {
                  reject(new Error('不存在文件'))
                }
                const type = file.type
                const size = file.size
                const whiteType = ['image/jpeg', 'image/png']
                if (whiteType.indexOf(type) === -1) { // 判断文件类型
                  reject(new Error('错误的文件类型'))
                }
                if (Math.ceil(size / 1024) < file_size) { // 判断文件大小
                  resolve(file)
                }
                const reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = e => {
                  const img = new Image()
                  img.src = e.target.result
                  img.onload = () => {
                    const ratio = img.naturalHeight / img.naturalWidth
                    const canvas = document.createElement('canvas')
                    const ctx = canvas.getContext('2d')
                    canvas.width = img.width > 750 ? 750 : img.width // 固定宽度
                    canvas.height = img.width * ratio
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
                    // limit:  0到1之间的取值,主要用来选定图片的质量,默认值是0.92,超出范围也会选择默认值。
                    const newImg = canvas.toDataURL('image/jpeg', limit)
                    // 将base64转换为filel流,
                    let flie= _this.convertBase64UrlToFile({
                        dataURL: newImg,
                        type: 'image/jpeg',
                        contentName: file.name
                    })
                    console.log('flie',flie)
                    _this.uploadImage(flie)
                  }
                }
              })
            },
            // 转base64
            convertBase64UrlToFile(base64) {
                let urlData = base64.dataURL
                let type = base64.type
                let contentName = base64.contentName
                let bytes = null
                if (urlData.split(',').length > 1) { //是否带前缀
                    bytes = window.atob(urlData.split(',')[1]) // 去掉url的头,并转换为byte
                } else {
                    bytes = window.atob(urlData)
                }
                // 处理异常,将ascii码小于0的转换为大于0
                let ab = new ArrayBuffer(bytes.length)
                let ia = new Uint8Array(ab)
                for (let i = 0; i < bytes.length; i++) {
                    ia[i] = bytes.charCodeAt(i)
                }
                let result = new Blob([ab], {
                    type: type,
                })
                let result1 = new File([result], contentName, {
                    type: type
                })
                result1.path = window.URL.createObjectURL(result)
                return result1
            },
            // 上传图片
            uploadImage(img) {
                console.log(img.path)
                 uni.uploadFile({
                    url: 'http://xxxxxx.cn/api/CKSelect',
                    filePath: img.path,
                    name: 'image',
                    success: (res) => {
                        uni.hideLoading()
                        const data = JSON.parse(res.data)
                        if (data.code == 200 && data.data) {
                            this.info = data.data
                        } else {
                            this.info = {}
                            uni.showModal({
                                content: data.msg || '查询失败',
                                showCancel: false,
                                success: function (res) {
                                    if (res.confirm) {
                                        that.images = require('../../static/img/up.png')
                                    }
                                }
                            })
                        }
                    },
                    fail: function(err) {
                        uni.hideLoading()
                        uni.showToast({
                            title: '失败',
                            icon: 'none'
                        })
                    }
                });
            }

相关文章

  • vue uniapp 图片压缩

    压缩的图片质量是从0到1的范围取值,数值越小,压缩的图片越小,我用的默认值0.921.02M --> 229KB2...

  • h5上传图片压缩

    涉及知识点 uniapp项目h5,涉及到前端图片压缩上传 uni.chooseImage() canvas压缩 参...

  • UniApp 压缩图片

    图片压缩不支持H5 获取文件path 文件压缩尝试 squoosh 测试 网站https://squoosh.ap...

  • vue(2019/7/15)

    vue实现照片选择或者拍照功能 照片格式校验, 图片质量压缩, 图片尺寸压缩, 图片离线保存, 图片base64编...

  • vue 图片压缩

    vue 图片压缩 上传图片大于100* 1024 的用canvas 来压缩来解决 然后IOS拍照上传会有图片旋转的...

  • vue 图片压缩

    vue 图片压缩 上传图片大于100* 1024 的用canvas来压缩来解决 然后IOS拍照上传会有图片旋转的问...

  • [性能优化]Webpack篇

    参考文章:Vue 项目性能优化 — 实践指南(网上最全 / 详细) Webpack 对图片进行压缩 在 vue 项...

  • Vue lrz 图片压缩

  • vue图片压缩lrz

    下载插件npm install lrz --save-dev

  • vue上传图片压缩

    第一个文件,afterRead方法是vant框架的上传获取原生文件流第二个文件,设置多一个方法postImg,设置...

网友评论

      本文标题:vue uniapp 图片压缩

      本文链接:https://www.haomeiwen.com/subject/tisavrtx.html