美文网首页
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 图片压缩

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