加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

【微信小程序】图片压缩-纯质量压缩,非长宽裁剪压缩

发布时间:2020-12-14 19:12:15 所属栏目:资源 来源:网络整理
导读:原理:利用canvas来实现,将图片绘制到canvas上,然后canvas转图片时,微信提供的一个方法wx.canvasToTempFilePath(Object object,Object this),此方式可以指定生成图片的质量,下图是从官方API截的图: 其中quality可以指定图片的质量,quality的值越小,

原理:利用canvas来实现,将图片绘制到canvas上,然后canvas转图片时,微信提供的一个方法wx.canvasToTempFilePath(Object object,Object this),此方式可以指定生成图片的质量,下图是从官方API截的图:

其中quality可以指定图片的质量,quality的值越小,图片越模糊,通过此方法可以实现图片的压缩

注意:

1.quality设置只对jpg格式的图片有效,使用时要将fileType设置为“jpg”, 此举可能会导致其它格式的图片变为jpg格式

2.透明背景的png图片,绘制到canvas上使用此方式导出的图片是黑色背景,有需求的话是需要canvas先设置背景色的,请小伙伴们注意爬坑。
复制代码

有了这个参数,压缩就简单很多了,下面是代码:

wxml

<view>
  <button bindtap="chooseImage">选择图片</button>
</view>

<!-- 展示压缩后的图片 -->
<view style="display: flex;justify-content: center;flex-direction: column">
  <image width="50" mode="widthFix" src="{{imagePath}}"></image>
</view>

<button wx:if={{imagePath.length>0}}" bindtap="save">点击下载压缩后的图片</button>

<!-- 用来渲染的canvas --> 
<canvas canvas-id='attendCanvasId' class='myCanvas' style='width:{{cWidth}}px;height:{{cHeight}}px;position: fixed;top: -9999px;left: -9999px;'></canvas>
复制代码

js

Page({
  data: {
    imagePath: '',quality: 0.2
  },onLoad: function (options) {
  
  },/**
  * 选项添加图片事件
  */
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['compressed'],136);">//可选择原图或压缩后的图片
      sourceType: ['album','camera'],136);">//可选择性开放访问相册、相机
      success: result => {
        wx.getImageInfo({
          src: result.tempFilePaths[0],success: function (res) {
            that.setData({
              cWidth: res.width,cHeight: res.height
            })
            that.getCanvasImg(result.tempFilePaths,res.width,res.height,that.data.quality,function (res) {
              that.setData({
                imagePath: res.tempFilePath
              });
            });
          }
        })
      }
    })
  },136);">/**
   * 质量压缩
   */
  getCanvasImg(tempFilePaths,canvasWidth,canvasHeight,quality,callback) {
    this; 
    const ctx = wx.createCanvasContext('attendCanvasId');
    ctx.clearRect(0,false,51); font-weight: 700;">function () {
      wx.canvasToTempFilePath({
        canvasId: 'attendCanvasId',fileType: 'jpg',quality: quality,51); font-weight: 700;">function success(res) {
          callback && callback(res)
        },fail: function (e) {
          wx.showToast({
            title: '图片上传失败,请重新上传!',icon: 'none'
          })
        }
      });
    });
  },136);">/**
   * 图片保存到相册
   */
  save(e) {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,51); font-weight: 700;">function (res) {
        console.log('图片已保存');
      },0);">'保存失败');
      }
    })
  },})
复制代码

注意点:

  1. 注意设置canvas-id='attendCanvasId'
  2. canvas要离屏渲染,就是移出屏幕之外,但是元素还是显示的,position: fixed;top: -9999px;left: -9999px; 不能使用 display: none; 这样是获取不到canvas元素的。

最后

h5页面中也有提供这样的方法

例如这样子:

let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
ctx.drawImage(imagePath,w,h);
canvas.toDataURL('image/jpeg',quality);
复制代码

需要的小伙伴也可以自己研究研究哈...

ok,结束, :clap:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读