Search code examples
nativescriptangular2-nativescriptnativescript-telerik-ui

Save image in nativescript


I have a scenario where I need to save an image from the <Image /> tag to the local file. The code does save the image to the file but i get an empty image, I know it's sound simple but I am new to NS and couldn't find anything on google, maybe someone knows why?

XML:

<page>
   <image src="pic.png" id="img"/>
</page>

JS:

let img       = page.getViewById("img");
let path      = fs.path.join(fs.knownFolders.documents().path, "pic.png");    
let src       = ImageSource.fromNativeSource(img);
let saved     = src.saveToFile(path, "png");

enter image description here


Solution

  • you might be getting empty image because of saving image before it is fully loaded. try saving image after it is fully loaded as shown in below snippet.

    To save image after it's load we are using loaded event and isLoading property of the Image.

    XML:

    <page>
       <image src="pic.png" loaded="onImageLoaded" id="img"/>
    </page>
    

    TS:

    onImageLoaded(args) {
        console.log(args.eventName);
        console.log(args.object);
    
        var img = args.object;
    
        console.log("img.isLoading: " + img.isLoading);
        console.log("img.isLoaded: " + img.isLoaded);
        if(img.isLoading){
    
            img.on("isLoadingChange", function (args) {
                console.log("isloading",args.value);
                console.log("isloaded",args.object.isLoaded);
                let img       = args.object;
                let path      = fs.path.join(fs.knownFolders.documents().path, "pic.png");    
                let src       = ImageSource.fromNativeSource(img);
                let saved     = src.saveToFile(path, "png");
            });
        }else if(!img.isLoading&&img.isLoaded){
            let path      = fs.path.join(fs.knownFolders.documents().path, "pic.png");    
            let src       = ImageSource.fromNativeSource(img);
            let saved     = src.saveToFile(path, "png");
        }else{
            console.log("image loading failed");
        }
    }