Image source

Using the image source requires the image-source module.

// const imageSource = require("image-source");

The pre-required imageSource module is used throughout the following code snippets. We also use fs module defined as follows:

// const fs = require("file-system");

Loading and saving images

Load image using resource name

This is similar to loading Bitmap from R.drawable.logo on Android or calling [UIImage imageNamed@"logo"] on iOS

const img = imageSource.fromResource("icon");

Load image from URL

    .then(function (res: imageSource.ImageSource) {
        //console.log("Image successfully loaded");
    }, function (error) {
        //console.log("Error loading image: " + error);

Save image source to PNG or JPG file

const img = imageSource.fromFile(imagePath);
const folder = fs.knownFolders.documents();
const path = fs.path.join(folder.path, "test.png");
const saved = img.saveToFile(path, "png");

Load image from a local file

const folder = fs.knownFolders.documents();
const path = fs.path.join(folder.path, "test.png");
const img = imageSource.fromFile(path);

Save image source from imageAsset to PNG file

import * as fs from "tns-core-modules/file-system";

export function imageSourceFromAsset(imageAsset){
    let source = new imageSource.ImageSource();
     source.fromAsset(imageAsset).then((source) => {
         let folder = fs.knownFolders.documents().path;
         let fileName = "test.png"
         let path = fs.path.join(folder, fileName);
         let saved = source.saveToFile(path, "png");
            console.log("saved image")

Stay connected with NativeScript

(expect a newsletter every 4-8 weeks)

NativeScript is licensed under the Apache 2.0 license .
© Progress Software Corporation. All Rights Reserved.