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('完成')
          },
        })
      }
    },
  })
}
相关推荐
前端不太难10 分钟前
《Vue 项目路由 + Layout 的最佳实践》
前端·javascript·vue.js
LYFlied13 分钟前
【每日算法】 LeetCode 56. 合并区间
前端·算法·leetcode·面试·职场和发展
想学后端的前端工程师35 分钟前
【Vue3组合式API实战指南:告别Options API的烦恼】
前端·javascript·vue.js
一勺-_-44 分钟前
mermaid图片如何保存成svg格式
开发语言·javascript·ecmascript
否子戈1 小时前
WebCut前端视频编辑UI框架一周开源进度
前端·音视频开发·ui kit
昔人'1 小时前
`corepack` 安装pnpm
前端·pnpm·node·corepack
萌萌哒草头将军1 小时前
pnpm + monorepo 才是 AI 协同开发的最佳方案!🚀🚀🚀
前端·react.js·ai编程
hboot2 小时前
💪别再迷茫!一份让你彻底掌控 TypeScript 类型系统的终极指南
前端·typescript
GISer_Jing2 小时前
深入拆解Taro框架多端适配原理
前端·javascript·taro
毕设源码-邱学长2 小时前
【开题答辩全过程】以 基于VUE的藏品管理系统的设计与实现为例,包含答辩的问题和答案
前端·javascript·vue.js