Search code examples
titaniumappceleratorappcelerator-titanium

Titanium - save remote image to filesystem


I'm building an app with titanium and I would like to save in the phone, the user's profile picture. In my login function, after the API response, I tried to do :

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);

And in the view in which I want to display the image :

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);

But the image doesn't appears. Could someone help me ?

Thanks a lot :)


Solution

  • There are 2 issues with your code:

    1 - You cannot use toImage() method unless your image view is rendered on UI stack or simply on display. Rather you should use toBlob() method.

    2 - Point no. 1 will also not work the way you are using because you cannot directly use toBlob() method until or unless the image from the url is completely loaded, means until it's shown on image view. To check when the image is loaded, use Ti.UI.ImageView onload event

    But, there's another better approach to do such type of tasks.

    Since you have the image url from your Login API response, you can use this url to fetch image from http client call like this:

    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();
    }