小程序保存图片到相册
发布于 6 年前 作者 fang25 15726 次浏览 来自 问答

现在小程序需要实现的一个需求是:点击页面的按钮,保存图片到本地的相册的功能。

在微信开发者工具上可以正常保存图片。

在真机的体验版上面,需要打开调试模式才可以正常保存。否则保存不了,页面一直在转圈(‘正在生成图片’),估计是报错了!

在正式版上面,就算开了调试模式都保存不了图片,页面一直在转圈(‘正在生成图片’)

我现在希望做一个保存图片到相册的功能,有实现过的吗?

下面是获取图片临时链接的代码

/**
* [@description](/user/description) 获取图片地址
**/
setImagePath(src){
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: src,
     success: function (res) {
resolve(res)
},
     fail:function () {
reject()
}
})
})
}

下面是保存图片函数的一些代码

//保存图片操作

saveImg(){

let _this = this;
       wx.showLoading({
title: '正在生成图片',
         mask: true,
       });
       let _bg='';
       if(_this.curPageRoute==='pages/index'){
_bg='http://fi.example.com/reb-pack-new-bg_02.jpg';
       }
else{
_bg='http://fi.example.com/receive_after2_02.png';
       }
let _qrCodePath=_this.qrCodePath;
       Promise.all([
_this.setImagePath(_bg),
         _this.setImagePath(_qrCodePath)]).then(res=>{
let ctx = wx.createCanvasContext('canvas',_this);
         ctx.setFillStyle('white');
         ctx.fillRect(0, 0, 750, 1206);
         //红包背景
   if(_this.curPageRoute==='pages/index'){
ctx.drawImage(res[0].path, 0, 0, 750, 1206);
         }
else{
ctx.drawImage(res[0].path, 0, 97, 750, 1109);
         }
         //小程序码
   ctx.drawImage(res[1].path, 262, 795, 225, 225);
         //金额
   ctx.setFontSize(66);
         ctx.setTextAlign('center');
         ctx.setFillStyle('#fff');
         let _amount=_this.amount;
         if(_amount.indexOf('.')!==-1){
_amount=_amount+'';
         }
ctx.fillText(_amount, 375, 460);
         //红包提示
   ctx.setFontSize(30);
         ctx.setTextAlign('center');
         ctx.setFillStyle('#f2df2e');
         ctx.fillText(_this.afterText, 375, 690);
         ctx.draw(false,function () {
wx.canvasToTempFilePath({
x: 0,
             y: 0,
             width: 750,
             height: 1206,
             destWidth: 750,
             destHeight: 1206,
             canvasId: 'canvas',
             fileType:'jpg',
             success: function(res) {
wx.saveImageToPhotosAlbum({
filePath:res.tempFilePath,
                 success:function () {
wx.hideLoading();
                   wx.showToast({
title: '保存成功',
                     icon: 'success',
                     duration: 1000
                   })
},
                 fail:function (e) {
wx.hideLoading();
                   wx.showToast({
title: '保存失败',
                     icon: 'success',
                     duration: 1000
                   })
}
});
             }
});
         });
       });
3 回复

解决了,安排下面排查下

  1. getImageInfo这个api对应的如果是一张不存在的图片,ios会报错.

  2. canvas画的图片必须要是https,并且在小程序后台的downloadFile设置域名的https.

也遇到同样的问题,楼主解决了嘛?

也遇到同样的问题,楼主解决了嘛?  有木有大神指导一二

回到顶部