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('完成')
          },
        })
      }
    },
  })
}
相关推荐
aesthetician2 小时前
Node.js v25 重磅发布!革新与飞跃:深入探索 JavaScript 运行时的未来
javascript·node.js·vim
2501_915918415 小时前
掌握 iOS 26 App 运行状况,多工具协作下的监控策略
android·ios·小程序·https·uni-app·iphone·webview
知识分享小能手5 小时前
uni-app 入门学习教程,从入门到精通,uni-app基础扩展 —— 详细知识点与案例(3)
vue.js·学习·ui·微信小程序·小程序·uni-app·编程
demi_meng6 小时前
reactNative 遇到的问题记录
javascript·react native·react.js
千码君20167 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
2501_915909067 小时前
iOS 混淆实战,多工具组合完成 IPA 混淆与加固(源码 + 成品 + 运维一体化方案)
android·运维·ios·小程序·uni-app·iphone·webview
赵庆明老师8 小时前
Uniapp微信小程序开发:EF Core 中级联删除
uni-app
lijun_xiao20099 小时前
前端最新Vue2+Vue3基础入门到实战项目全套教程
前端
90后的晨仔9 小时前
Pinia 状态管理原理与实战全解析
前端·vue.js
杰克尼9 小时前
JavaWeb_p165部门管理
java·开发语言·前端