直接上代码:

选择图片

chooseAvatar(){
	uni.chooseImage({
		count:1,
		success: (res) => {
			this.handleUpload(res.tempFilePaths[0])
		}
	})
},

获取文件大小的方法

getFileSize(filePath) {
	return new Promise((resolve, reject) => {
		uni.getFileInfo({
			filePath: filePath,
			success: function(res) {
				const fileSize = res.size;
				resolve(fileSize);
			},
			fail: function(err) {
				reject(err);
			}
		});
	});
},

压缩文件

export default function compressPhoto(imagePath) {
  const maxSize = 200 * 1024; // 设置最大文件大小为 200KB
  const step = 10; // 每次迭代减少的压缩质量值
  let quality = 80; // 初始压缩质量为80

  return new Promise((resolve, reject) => {
    function compress() {
      uni.compressImage({
        src: imagePath,
        quality: quality,
        success: function(res) {
          const compressedImagePath = res.tempFilePath;

          uni.getFileInfo({
            filePath: compressedImagePath,
            success: function(res) {
              const fileSize = res.size;

              if (fileSize <= maxSize || quality <= 0) {
                // 图片大小符合要求,返回压缩后的图片路径
                resolve(compressedImagePath);
              } else {
                // 继续迭代压缩图片大小
                quality -= step;
                retry();
              }
            },
            fail: function(err) {
              // 获取文件信息失败,返回错误信息
              reject(err);
            }
          });
        },
        fail: function(err) {
          // 压缩图片失败,返回错误信息
          reject(err);
        }
      });
    }

    function retry() {
      if (quality > 0) {
        compress();
      } else {
        reject(new Error('压缩图片失败'));
      }
    }

    retry();
  });
}

执行

async handleUpload(imagePath) {
			try{
				const maxSize = 200 * 1024; // 设置最大文件大小为 200KB
				const fileSize = await this.getFileSize(imagePath);
				if (fileSize > maxSize) {
					console.log('已超出最大200kb限制,正在压缩中....');
					const compressedImagePath = await compressPhoto(imagePath);
					await this.uploadImage(compressedImagePath); // 调用上传图片的方法,传入压缩后的图片路径
				} else {
					console.log('未超出最大200kb限制,正常上传中....');
					await this.uploadImage(imagePath); // 调用上传图片的方法,传入原始图片路径
				}
			}catch(error){
				console.log('图片处理或上传失败', error);
			}
		},
uploadImage为你上传到服务器的方法,自己写吧,compressedImagePath是压缩过的url
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐