【问题标题】:Titanium - save remote image to filesystemTitanium - 将远程图像保存到文件系统
【发布时间】:2017-01-15 21:06:26
【问题描述】:

我正在用钛构建一个应用程序,我想在手机中保存用户的个人资料图片。在我的登录功能中,在 API 响应之后,我尝试这样做:

Ti.App.Properties.setString("user_picture_name", res.profil_picture);
var image_to_save = Ti.UI.createImageView({image:img_url}).toImage();
var picture = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, res.profil_picture); //As name, the same as the one in DB
picture.write(image_to_save);

在我想要显示图像的视图中:

var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,Ti.App.Properties.getString("user_picture_name") );

var image = Ti.UI.createImageView({
    image:f.read(),
    width:200,
    height:100,
    top:20
});
main_container.add(image);

但是图像没有出现。有人可以帮我吗?

非常感谢:)

【问题讨论】:

    标签: titanium appcelerator appcelerator-titanium


    【解决方案1】:

    您的代码有 2 个问题:

    1 - 您不能使用 toImage() 方法,除非您的图像视图呈现在 UI 堆栈上或只是在显示上。相反,您应该使用 toBlob() 方法。

    2 - 点号。 1 也不会以您使用的方式工作,因为您不能直接使用 toBlob() 方法,直到或除非来自 url 的图像完全加载,这意味着直到它显示在图像视图上。要检查图像何时加载,请使用 Ti.UI.ImageView onload event

    但是,还有另一种更好的方法来执行此类任务。

    由于您从登录 API 响应中获得了图像 url,因此您可以使用此 url 从 http 客户端调用中获取图像,如下所示:

    function fetchImage() {
        var xhr = Ti.Network.createHTTPClient({
            onerror : function() {
                alert('Error fetching profile image');
            },
    
            onload : function() {
                // this.responseData holds the binary data fetched from url
                var image_to_save = this.responseData;
    
                //As name, the same as the one in DB
                var picture = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, res.profil_picture);
                picture.write(image_to_save);
    
                Ti.App.Properties.setString("user_picture_name", res.profil_picture);
    
                image_to_save = null;
            }
        });
    
        xhr.open("GET", img_url);
        xhr.send();
    }
    

    【讨论】:

    • 您应该将答案标记为正确,以感谢 Prashant 并帮助其他用户在未来找到可行的解决方案。 :)
    【解决方案2】:

    你不需要手动缓存远程图片,因为

    远程图像会自动缓存在 iOS 平台上,因为 版本 3.1.0,在 Android 平台上。

    [see docs here & credit to Fokke Zandbergen]

    只需在您的 UI 中使用远程图像 url,第一次访问 Titanium 会为您下载并缓存它;下一次访问相同的图像 url 实际上将在本地设备上自动缓存的版本上(没有代码是最好的代码)

    Hth.

    【讨论】:

    • 此解决方案仅适用于修复 url。如果图像 url 发生变化,那么它将不起作用。
    • 好吧,我猜这值得一提。感谢您的反对
    • 是的,很高兴提及,但它与这个问题无关,我们应该始终尝试将实际答案直接指向问题,而不是提及用户未询问的其他内容。由于他提到他想将图片保存在存储中,这也意味着他将进一步使用此图像,如更新裁剪、调整大小等。对不起,投反对票。 :)
    • 完全没问题 Prashant,很好,感谢您花时间解释它。我明白你的意思,看来我错过了他的问题的意思。问候。
    • 感谢您的回答。我不想修改这张图片,只是在用户离线时显示。我不知道这个缓存,我也试过你的解决方案。但是当我离线时,图片不在这里......所以,这是正常的事情吗?
    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多