uni小程序长按保存图片
1 <!-- #ifdef APP-PLUS --> 2 <image :src="图片地址" mode="aspectFill" @longpress="savePhoto(图片地址)"/> 3 <!-- #endif --> 4 <!-- #ifdef MP --> 5 <image :src="图片地址" mode="aspectFill" @longpress="savePosterPath(图片地址)"/> 6 <!-- #endif -->
app端
1 // APP保存图片 2 savePhoto(url) { 3 // 先下载图片 4 uni.downloadFile({ 5 url, 6 success: (res) => { 7 // 获取到图片本地地址后再保存图片到相册(因为此方法不支持远程地址) 8 uni.saveImageToPhotosAlbum({ 9 filePath: res.tempFilePath, 10 success: () => { 11 uni.showToast({ 12 title: "保存成功!", 13 }); 14 }, 15 fail: () => { 16 uni.showToast({ 17 title: "保存失败", 18 }); 19 }, 20 }); 21 }, 22 }); 23 },
小程序端
1 savePosterPath(url) { 2 uni.downloadFile({ 3 url, 4 success: (resFile) => { 5 console.log(resFile, "resFile"); 6 if (resFile.statusCode === 200) { 7 uni.getSetting({ 8 success: (res) => { 9 if (!res.authSetting["scope.writePhotosAlbum"]) { 10 uni.authorize({ 11 scope: "scope.writePhotosAlbum", 12 success: () => { 13 uni.saveImageToPhotosAlbum({ 14 filePath: resFile.tempFilePath, 15 success: (res) => { 16 return uni.showToast({ 17 title: "保存成功!", 18 }); 19 }, 20 fail: (res) => { 21 return uni.showToast({ 22 title: res.errMsg, 23 }); 24 }, 25 complete: (res) => {}, 26 }); 27 }, 28 fail: () => { 29 uni.showModal({ 30 title: "您已拒绝获取相册权限", 31 content: "是否进入权限管理,调整授权?", 32 success: (res) => { 33 if (res.confirm) { 34 uni.openSetting({ 35 success: (res) => { 36 console.log(res.authSetting); 37 }, 38 }); 39 } else if (res.cancel) { 40 return uni.showToast({ 41 title: "已取消!", 42 }); 43 } 44 }, 45 }); 46 }, 47 }); 48 } else { 49 uni.saveImageToPhotosAlbum({ 50 filePath: resFile.tempFilePath, 51 success: (res) => { 52 return uni.showToast({ 53 title: "保存成功!", 54 }); 55 }, 56 fail: (res) => { 57 return uni.showToast({ 58 title: res.errMsg, 59 }); 60 }, 61 complete: (res) => {}, 62 }); 63 } 64 }, 65 fail: (res) => {}, 66 }); 67 } else { 68 return uni.showToast({ 69 title: resFile.errMsg, 70 }); 71 } 72 }, 73 fail: (res) => { 74 return uni.showToast({ 75 title: res.errMsg, 76 }); 77 }, 78 }); 79 },
app|小程序baocunbase64至本地
saveBase64Img(base64) { // #ifdef APP-PLUS let imageStr = "data:image/png;base64," + base64; // 保存到本地 let bitmap = new plus.nativeObj.Bitmap("goods_poster"); bitmap.loadBase64Data( imageStr, () => { console.log("加载Base64图片数据成功"); bitmap.save( "_doc/goods_poster.png", {}, (i) => { console.log("保存图片成功:" + JSON.stringify(i)); bitmap.clear(); }, (e) => { onsole.log("保存图片失败:" + JSON.stringify(e)); bitmap.clear(); } ); }, (e) => { console.log("加载Base64图片数据失败:" + JSON.stringify(e)); bitmap.clear(); } ); // #endif // #ifdef MP var fileManager = uni.getFileSystemManager(); fileManager.writeFile({ filePath: "/img.jpg", // 指定图片的临时路径 data: base64, // 要写入的文本或二进制数据 encoding: "base64", // 指定写入文件的字符编码 success: (res) => { console.log("写入文件成功,文件路径信息为:", res); 转换本地路径成功后这里可以用上面的图片保存方法 }, file: (err) => { console.log("写入文件失败", err); }, }); // #endif }
资料来自:https://www.jianshu.com/p/bb3b61271991