【问题标题】:Cannot Save Images from URL in Nativescript/Javascript with imageSource module无法使用 imageSource 模块从 Nativescript/Javascript 中的 URL 保存图像
【发布时间】:2017-01-27 19:02:39
【问题描述】:

上下文

我正在尝试将用户的 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() 的输出是布尔值:

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

...但是这也没有输出任何内容。

问题

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

参考文献

【问题讨论】:

  • 嗨,Ben,你能做到吗?

标签: javascript android image nativescript


【解决方案1】:

我认为这里的主要问题在于那一行,因为 ImageSource 仅适用于本地文件,而不适用于 url:

var img = imageSource.fromFile("http://graph.facebook.com/"+user.id+"/picture?type=large");


您应该下载图片,而不是从 url 设置来源。关于下载图像,您可以在此处阅读: 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,只是查看了文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-24
    • 2019-03-22
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2015-08-22
    • 1970-01-01
    相关资源
    最近更新 更多