在开发过程中经常遇到保存图片到相册的需求,主要有两种一是保存服务器地址图片,还有一种是保存 canvas 生成的 base64 格式图片,下面来讲解分别怎么实现。
保存服务器地址图片到相册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| wx.getSetting({ success: (res) => { if (!res.authSetting["scope.writePhotosAlbum"]) { wx.authorize({ scope: "scope.writePhotosAlbum", success: () => { saveToAlbum(); }, fail: () => { }, }); } else { saveToAlbum(); } }, });
function saveToAlbum() { wx.downloadFile({ url: imgUrl, success: function (res) { wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success(res) { }, fail: () => { }, }); }, fail: () => { }, }); }
|
保存 base64 格式图片到相册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| wx.getSetting({ success: (res) => { if (!res.authSetting["scope.writePhotosAlbum"]) { wx.authorize({ scope: "scope.writePhotosAlbum", success: () => { saveToAlbum(); }, fail: () => { }, }); } else { saveToAlbum(); } }, });
function saveToAlbum() { const buffer = wx.base64ToArrayBuffer( img.replace(/^data:\w+\/\w+;base64,/, "") ); const path = `${wx.env.USER_DATA_PATH}/image_name.png`; const fsm = wx.getFileSystemManager(); fsm.writeFile({ filePath: path, data: params, encoding: "binary", success: () => { wx.saveImageToPhotosAlbum({ filePath: path, success: () => { }, fail: () => { }, }); }, fail: () => { }, }); }
|