微信小程序之生成图片保存到相册
发布日期:2021-05-10 03:43:26 浏览次数:23 分类:精选文章

本文共 5787 字,大约阅读时间需要 19 分钟。

微信小程序生成图片保存到相册方法

在电商项目中,将商品信息与小程序码生成海报并保存到手机相册,方便分享至多平台以扩大曝光面。以下是实现该功能的详细步骤和思路。

需求概要

系统需求包括以下关键点:

  • 需要显示商品信息和用户信息
  • 需要生成三种不同格式的海报
  • 海报可通过左右滑动切换
  • 提供保存海报功能到本地相册
  • 海报内容包括商品图片、价格、名称、描述和二维码
  • 思路总结

  • 获取商品信息和用户信息
  • 使用swiper组件展示海报内容
  • 通过wx.createCanvasContext绘制海报到画布
  • 使用canvasToTempFilePath保存海报到本地临时存储路径
  • 调用saveImageToPhotosAlbum保存海报到手机相册
  • 判断swiper组件的当前滑块位置以确定保存的海报格式
  • 解决方案

    按照思路逐步实现如下:

  • 获取商品信息和用户信息
  • // index.js 中的导航事件处理函数
    navToShare: function() {
    var data = {
    thumb_images: [
    'https://cbu01.alicdn.com/img/ibank/2018/544/692/8567296445_882293189.400x400.jpg',
    'https://cbu01.alicdn.com/img/ibank/2018/971/643/8581346179_882293189.400x400.jpg',
    'https://cbu01.alicdn.com/img/ibank/2018/184/392/8567293481_882293189.400x400.jpg'
    ],
    name: '2018夏季新款镂空圆领蝙蝠短袖t恤女装韩版宽松棉小衫上衣批发潮',
    price: 198,
    };
    wx.navigateTo({
    url: '../poster/poster?data=' + encodeURIComponent(JSON.stringify(data))
    });
    }
    1. 海报页面渲染
    2. // poster.js 中的onLoad函数
      onLoad: function(options) {
      var data = JSON.parse(decodeURIComponent(options.data));
      var userinfo = wx.getStorageSync('userInfo');
      this.setData({
      avatar_url: userinfo.avatarUrl,
      nickname: userinfo.nickName,
      thumb_images: data.thumb_images,
      pro_price: data.price,
      pro_name: data.name
      });
      // 获取并缓存商品图片
      wx.getImageInfo({
      src: userinfo.avatarUrl,
      success: function(res) {
      tmpAvatarUrl = res.path;
      }
      });
      // 获取并缓存商品图标
      var thumbs = data.thumb_images;
      tmpThumbs = [];
      thumbs.forEach(function(item, i) {
      wx.getImageInfo({
      src: item,
      success: function(res) {
      tmpThumbs.push(res.path);
      }
      });
      });
      }
      1. 小程序码生成
      2. // 封装后的POST方法
        wxRequest.postRequest(url, data).then(function(res) {
        if (res.data.error_code == 0) {
        wx.getImageInfo({
        src: res.data.qrcode,
        success: function(result) {
        this.setData({
        poster_qrcode: result.path
        });
        }
        });
        }
        });
        1. 使用swiper组件展示海报
          1. canvas绘制海报
          2. // 在wxml中添加canvas组件
            /*样式定义*/
            .canvas-poster {
            position: fixed;
            width: 280px;
            height: 450px;
            top: 100%;
            left: 100%;
            overflow: hidden;
            }
            /*海报绘制逻辑 */
            drawPosterOne: function() {
            var ctx = wx.createCanvasContext('canvasposter');
            ctx.clearRect(0, 0, 280, 450);
            ctx.beginPath();
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, 280, 450);
            ctx.fillStyle = '#333';
            ctx.fontSize = 16;
            ctx.textAlign = 'center';
            ctx.fillText(this.data.nickname + '的小店', 140, 70);
            ctx.drawImage(tmpThumbs[0], 35, 90, 210, 210);
            ctx.fillStyle = '#FF8409';
            ctx.fillRect(35, 300, 210, 60);
            ctx.fillStyle = '#ffffff';
            ctx.fontSize = 12;
            ctx.textAlign = 'left';
            ctx.fillText(this.data.pro_name.substr(0, 18), 45, 322);
            ctx.fontSize = 12;
            ctxilinStyle = '#ffffff';
            ctx.fillText(this.data.pro_name.substr(18, 20), 45, 344);
            ctx.setLineDash([1, 3], 1);
            ctx.beginPath();
            ctx.moveTo(35, 375);
            ctx.lineTo(160, 375);
            ctx.moveTo(35, 435);
            ctx.lineTo(160, 435);
            ctx.strokeStyle = '#979797';
            ctx.stroke();
            ctx.restore();
            ctx.fillStyle = '#333333';
            ctx.fontSize = 14;
            ctx.fillText('¥', 35, 400);
            ctx.fontSize = 18;
            ctx.fillText(this.data.pro_price, 50, 400);
            ctx.fontSize = 11;
            ctx.fillStyle = '#666666';
            ctx.fillText(this.data.poster_qrtext, 35, 420);
            ctx.restore();
            ctx.drawImage(this.data.poster_qrcode, 185, 370, 60, 60);
            ctx.restore();
            ctx.draw(false, this.getTempFilePath());
            }
            1. 使用canvasToTempFilePath将海报换成本地路径
            2. getTempFilePath: function() {
              wx.canvasToTempFilePath({
              canvasId: 'canvasposter',
              success: function(res) {
              this.saveImageToPhotosAlbum(res.tempFilePath);
              }
              });
              }
              1. 保存到相册的方法
              2. saveImageToPhotosAlbum: function(imgUrl) {
                if (imgUrl) {
                wx.saveImageToPhotosAlbum({
                filePath: imageUrl,
                success: function(res) {
                wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
                });
                drawing = false;
                },
                fail: function(err) {
                wx.showToast({
                title: '保存失败',
                icon: 'none',
                duration: 2000
                });
                drawing = false;
                }
                });
                } else {
                wx.showToast({
                title: '绘制中……',
                icon: 'loading',
                duration: 3000
                });
                }
                }
                1. 判断当前海报并保存
                2. shareChange: function(e) {
                  if (e.detail.source == 'touch') {
                  this.setData({
                  current: e.detail.current
                  });
                  }
                  }
                  1. 绘制海报并保存
                  2. savePoster: function(e) {
                    var that = this;
                    var current = that.data.current;
                    wx.getSetting({
                    success: function(res) {
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: function() {
                    that.drawPoster(current);
                    },
                    fail: function() {
                    wx.showModal({
                    title: '提示',
                    content: '如未打开设置,无法保存图片!',
                    showCancel: true,
                    cancelText: '去设置',
                    confirmText: '暂不开启',
                    confirmColor: '#3CC51F',
                    success: function(res) {
                    if (res) {
                    wx.openSetting();
                    }
                    }
                    });
                    that.drawPoster(current);
                    }
                    });
                    } else {
                    that.drawPoster(current);
                    }
                    }
                    });
                    }
                    1. 判断当前滑块绘制对应海报
                    2. drawPoster: function(current) {
                      if (drawing) {
                      wx.showToast({
                      title: '绘制中……',
                      icon: 'loading',
                      duration: 3000
                      });
                      } else {
                      drawing = true;
                      switch (current) {
                      case 0:
                      this.drawPosterOne();
                      break;
                      case 1:
                      this.drawPosterTwo();
                      break;
                      case 2:
                      this.drawPosterThree();
                      break;
                      }
                      }
                      }

                      通过以上方法,您可以轻松将商品信息整合成海报并保存到手机相册,方便用户分享。

    上一篇:自适应 CSS 栅格布局
    下一篇:在微信小程序上,帮助中心界面实现类似手风琴案例

    发表评论

    最新留言

    哈哈,博客排版真的漂亮呢~
    [***.90.31.176]2025年04月14日 00时33分33秒