首页 文章

无法使用imageSource模块从Nativescript / Javascript中保存URL中的图像

提问于
浏览
1

上下文

我正在尝试将用户的Facebook Profiles 图片下载到本地存储,以便我可以显示它而无需重新调用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() 的输出是布尔值:

if(img.saveToFile(path, enums.ImageFormat.jpg)) console.log("success");
    else console.log("failure");

......但是这也没有输出任何东西 .

问题

如何将图像从URL保存到设备的本地存储?

参考

1 回答

  • 0

    我认为主要的麻烦在于该行,因为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,只是查看了文档 .

相关问题