上下文
我正在尝试将用户的 Facebook 个人资料图片下载到本地存储,以便无需重新调用 Facebook 即可显示它。
代码
我使用模块image-source
来下载图像,并使用模块file-system
来访问设备的本地存储。
大部分代码都引用 the Nativescript image-source
documentation page .
var imageSource = require("image-source");
var fs = require("file-system");
exports.theFunction = function(args){
//...
var img = imageSource.fromFile("http://graph.facebook.com/"+user.id+"/picture?type=large");
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "profilePic.jpg");
console.log(path);
var saved = img.saveToFile(path, enums.ImageFormat.jpg);
appSettings.setString("imgLocal",path);
console.log("Image Saved Successfully");
//...
}
输出
/data/user/0/com.foo.bar/files/profilePic.jpg
我从未看到“图像已成功保存”消息输出到控制台,并且无法使用模拟器验证图像是否已存储在文件系统中(我正在为没有设备的 Android 进行开发)。
我还尝试将保存事件包装在 if
标记中,假设 saveToFile()
的输出是 bool 值:
if(img.saveToFile(path, enums.ImageFormat.jpg)) console.log("success");
else console.log("failure");
...但是这也没有输出任何内容。
问题
如何将 URL 中的图像保存到设备的本地存储?
引用文献
最佳答案
我认为这里的主要问题在于该行,因为 ImageSource 仅适用于本地文件,不适用于网址:
var img = imageSource.fromFile("http://graph.facebook.com/"+user.id+"/picture?type=large");
您应该下载图像,而不是从网址设置源。关于下载图像,您可以在这里阅读:
https://docs.nativescript.org/cookbook/ui/image-cache
或者尝试这样的事情并以某种方式保存它:
var image = new ImageModule.Image();
image.src = "https://www.google.com/images/errors/logo_sm_2.png";
但对此我不太确定。我从未使用过 NativeScript,只是浏览了文档。
关于javascript - 无法使用 imageSource 模块在 Nativescript/Javascript 中保存 URL 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41901213/