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('完成')
          },
        })
      }
    },
  })
}
相关推荐
Struggler2811 分钟前
SSE的使用
前端
用户5806139393008 分钟前
前端文件下载实现深度解析:Blob与ObjectURL的完美协作
前端
Lin866611 分钟前
Vue 3 + TypeScript 组件类型推断失败问题完整解决方案
前端
coding随想11 分钟前
从零开始:前端开发者的SEO优化入门与实战
前端
前端工作日常14 分钟前
我理解的JSBridge
前端
Au_ust14 分钟前
前端模块化
前端
顺丰同城前端技术团队14 分钟前
还不会用 Charles?最后一遍了啊!
前端
BUG收容所所长15 分钟前
二分查找的「左右为难」:如何优雅地找到数组中元素的首尾位置
前端·javascript·算法
彬师傅15 分钟前
geojson、csv、json 数据加载
前端
用户527096487449016 分钟前
🔥 我与 ESLint 的爱恨纠葛:从"这破玩意儿"到"真香警告"
前端