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('完成')
          },
        })
      }
    },
  })
}
相关推荐
爱吃的强哥2 分钟前
vue3 使用 vite 管理多个项目,实现各子项目独立运行,独立打包
前端·javascript·vue.js
涵信10 分钟前
第十节:性能优化高频题-虚拟DOM与Diff算法优化
javascript·vue.js·性能优化
谈不譚网安11 分钟前
CSRF请求伪造
前端·网络安全·csrf
TT模板16 分钟前
苹果cmsV10主题 MXonePro二开优化修复开源版
前端·html5
拖孩17 分钟前
【Nova UI】十一、组件库中 Icon 组件的测试、使用与全局注册全攻略
前端·javascript·vue.js·ui·sass
去伪存真22 分钟前
不用动脑,手把手跟着我做,就能掌握Gitlab+Jenkins提交代码自动构部署
前端·jenkins
天天扭码1 小时前
深入解析 JavaScript 中的每一类函数:从语法到对比,全面掌握适用场景
前端·javascript·面试
小希爸爸1 小时前
4、中医基础入门和养生
前端·后端
kooboo china.1 小时前
Tailwind CSS 实战:基于 Kooboo 构建企业官网页面(一)
前端·css·编辑器
uhakadotcom1 小时前
Fluid:云原生数据加速与管理的简单入门与实战
前端