background

Recently, the product introduced a small program to save pictures. Applet preview originally supported long press to save the picture, but considering that some users do not know this function, can only make a save picture button.

The problem

The ability to save images seems simple enough. But I ran into the following problems while doing so.

  • Image url

Wx saveImageToPhotosAlbum method only support save the local path, does not support network path, you need to use the wx. DownloadFile download file to the local resources, local path to images.

  • Compatibility issues

The compatibility problem refers to that the image to be saved in our project is a GET interface address, which returns the file stream of the image, so that its URL is not the standard PNG/JPG suffix format. After the test, it can be saved on wechat developer tool and iPhone, but an error will be reported on Android phone. “SaveImageToPhotosAlbum: fail invalid file type”, is in fact the picture type errors. We can add the filePath attribute to wx.downloadFile and manually append the image suffix. The code looks like this:

saveImageToPhotosAlbum() { const that = this; wx.downloadFile({ url: this.qrCode, filePath: `${wx.env.USER_DATA_PATH}/${Date.now()}.jpg`, success(result) { wx.saveImageToPhotosAlbum({ filePath: Result. FilePath, success(res) {that.$toast(' image saved successfully ', 'success'); }, fail(err) { console.log(err); That.$toast(' image failed to save '); }}); }}); }Copy the code
  • Authorization problem

The applet initiates the “Save picture” authorization when saving the picture. We need to judge three situations: unauthorized, denied, and successful authorization. You can use the wx.getSetting method to get the user’s authorization status. The code is as follows:

saveImageEvent() { const settingId = 'scope.writePhotosAlbum'; getAuthSetting('authSetting', settingId).then(writePhotosAlbum => { const that = this; console.log('writePhotosAlbum', writePhotosAlbum); If (writePhotosAlbum === undefined) {// Authorize wx.authorize({scope: authorize) settingId, success() { that.saveImageToPhotosAlbum(); }, fail(res) {that.$toast(' grant failed '); }}); } else if (writePhotosAlbum === false) { Open the authorization Settings wx. OpenSetting ({success (res) {if (res) authSetting [settingId]) {that. SaveImageToPhotosAlbum (); }}, fail() {that.$toast(' grant failed '); }}); } else { this.saveImageToPhotosAlbum(); }}); } @param {*} settingType settingType: authSetting, subscriptionsSetting @param {*} settingId settingId: */ export function getAuthSetting(settingType, settingId) {return new Promise(resolve, reject) => { wx.getSetting({ withSubscriptions: true, success(response) { console.log(response); resolve(response[settingType][settingId]); }}); }).catch(res => { console.log(res); }); }Copy the code

Refer to the article: https://juejin.cn/post/6844904166070943751