加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

mp-image-compress 小程序图片压缩接口(图片压缩至指定大小),并返回 width, height, size

为规范前端用户上传照片的大小,减轻存储服务器压力,当用户选取的照片过大时,在前端自动进行压缩至指定大小(比如 1M )后再上传。

1 - 仓库地址

2 - 测试环境

  • 微信小程序基础库版本:2.32.3 及以上

3 - 安装方法:npm安装

npm i mp-image-compress --save

依赖包安装后,需要在小程序开发者工具中:构建npm

4 - 接口使用示例

index.js

// 引用 mp-image-compress
import mpImageCompress from 'mp-image-compress'

Page({
  data: {
    img: ''
  },
  onLoad() {
    mpImageCompress.clearTempImg() // 页面载入时清除临时文件
  },
  onUnload() {
    mpImageCompress.clearTempImg()  // 页面卸载时清除临时文件
  },
  chooseImage() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      async success(res) {
        const info = res.tempFiles[0]

        // 选择文件后调用图片压缩接口进行压缩。如果选取的图片没有达到指定的大小,将返回原图

        const imgRes = await mpImageCompress.set(info.tempFilePath, 1024) // 1024K
        console.info(imgRes)

        ///////////////////////

        that.setData({
          img: imgRes.filePath
        })
      }
    })
  },
  preview() {
    wx.previewImage({
      current: this.data.img,
      urls: [this.data.img]
    })
  },
  DelImg() {
    this.setData({
      img: ''
    })
  },
})
MIT License Copyright (c) 2023 WeiDoctor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

微信小程序图片压缩接口(图片压缩至指定大小),并返回 width, height, size 展开 收起
JavaScript
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化