uniapp H5上传图片前压缩

问题:需要在上传图片前压缩图片,但是uni.compressImage()不支持h5

解决方法:使用canvas降低图片质量

核心代码:

复制代码
 // 创建一个 img 元素来加载图片
      const img = new Image()
      img.src = imagePath


 // 创建 canvas 元素
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        // 设置 canvas 的宽高为压缩后的图片宽高
        const maxWidth = 800 // 最大宽度
        const maxHeight = 800 // 最大高度
        let width = img.width
        let height = img.height

        // 根据最大宽高比例调整图片尺寸
        if (width > height) {
          if (width > maxWidth) {
            height = height * (maxWidth / width)
            width = maxWidth
          }
        } else {
          if (height > maxHeight) {
            width = width * (maxHeight / height)
            height = maxHeight
          }
        }

        // 设置 canvas 尺寸
        canvas.width = width
        canvas.height = height

        // 绘制压缩后的图片到 canvas 上
        ctx.drawImage(img, 0, 0, width, height)
        // 调整图片质量的函数,直到大小小于 500KB
        function compressImage(quality) {
          const compressedImage = canvas.toDataURL('image/jpeg', quality) // 质量控制
          const size = (compressedImage.length * 3) / 4 / 1024 // 计算压缩后的大小,单位为 KB

          if (size > 500 && quality > 0.1) {
            // 如果图片大于500KB,降低质量重新压缩
            return compressImage(quality - 0.05)
          } else {
            // 如果图片小于500KB,或者达到最低质量,返回结果
            return compressedImage
          }
        }

        const compressedImage = compressImage(0.8) // 初始质量为 0.8

完整代码:

复制代码
function fromAlbum() {
  uni.chooseImage({
    count: 1, // 默认选择 1 张图片
    sizeType: ['original', 'compressed'], // 选择原图或压缩图
    success: function (res) {
      uni.setStorage({
        key: 'tongueData',
        data: '',
      })
      tongueImageSrc.value = ''
      const imagePath = res.tempFilePaths[0] // 获取选中的图片路径
      // 创建一个 img 元素来加载图片
      const img = new Image()
      img.src = imagePath

      img.onload = function () {
        // 创建 canvas 元素
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        // 设置 canvas 的宽高为压缩后的图片宽高
        const maxWidth = 800 // 最大宽度
        const maxHeight = 800 // 最大高度
        let width = img.width
        let height = img.height

        // 根据最大宽高比例调整图片尺寸
        if (width > height) {
          if (width > maxWidth) {
            height = height * (maxWidth / width)
            width = maxWidth
          }
        } else {
          if (height > maxHeight) {
            width = width * (maxHeight / height)
            height = maxHeight
          }
        }

        // 设置 canvas 尺寸
        canvas.width = width
        canvas.height = height

        // 绘制压缩后的图片到 canvas 上
        ctx.drawImage(img, 0, 0, width, height)

        // 调整图片质量的函数,直到大小小于 500KB
        function compressImage(quality) {
          const compressedImage = canvas.toDataURL('image/jpeg', quality) // 质量控制
          const size = (compressedImage.length * 3) / 4 / 1024 // 计算压缩后的大小,单位为 KB

          if (size > 500 && quality > 0.1) {
            // 如果图片大于500KB,降低质量重新压缩
            return compressImage(quality - 0.05)
          } else {
            // 如果图片小于500KB,或者达到最低质量,返回结果
            return compressedImage
          }
        }

        const compressedImage = compressImage(0.8) // 初始质量为 0.8

        // 上传压缩后的图片
        
        uni.uploadFile({
          url: ,//填自己的路径
          filePath: compressedImage, // 上传压缩后的图片
          name: 'file',
          
          success: async (uploadFileRes) => {
            const { code, data, msg } = JSON.parse(uploadFileRes.data) || {}

            if (code === 0 && data && data.local_path) {
             console.log('上传图片成功')
            } else {
             console.log('上传图片失败')
            }
          },
          complete: () => {
            console.log('完成')
          },
        })
      }
    },
  })
}
相关推荐
神奇的程序员3 小时前
我的软件冲进苹果商店下载榜前 50 了
前端
阳光是sunny4 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
万少5 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童7 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒8 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜9 小时前
Flutter 国内安装指南
前端·flutter
先吃饱再说9 小时前
JavaScript中`this` 的“千层套路”:从默认绑定到箭头函数的五种指向
javascript
玄星啊9 小时前
AI 编程的第 30 天,我怀念古法 Coding 了
前端·ai编程
Jolyne_9 小时前
Angular基础速通
前端·angular.js
foxire9 小时前
基于nodejs实现服务端内核引擎
javascript