NativeScript Core Modules compatibility package for building native iOS and Android apps using JavaScript and CSS
—
Comprehensive image loading, manipulation, and caching capabilities for mobile applications. The image handling system supports multiple image sources, format conversion, and efficient memory management.
Core image representation class providing image loading and manipulation functionality.
/**
* Image source class for image loading and manipulation
*/
class ImageSource {
// Static factory methods
static fromFile(path: string): ImageSource;
static fromData(data: any): ImageSource;
static fromBase64(source: string): ImageSource;
static fromResource(name: string): ImageSource;
static fromUrl(url: string): Promise<ImageSource>;
static fromAsset(asset: ImageAsset): Promise<ImageSource>;
// Properties
readonly width: number;
readonly height: number;
readonly rotationAngle: number;
// File operations
saveToFile(path: string, format: "png" | "jpeg", quality?: number): boolean;
toBase64String(format: "png" | "jpeg", quality?: number): string;
// Image manipulation
resize(maxSize: number, options?: ResizeOptions): ImageSource;
// Platform-specific native access
readonly android: any; // Android Bitmap
readonly ios: any; // iOS UIImage
}
/**
* Image resize options
*/
interface ResizeOptions {
maxWidth?: number;
maxHeight?: number;
aspectRatio?: "aspectFill" | "aspectFit";
quality?: number;
}Usage Examples:
import { ImageSource, knownFolders } from "tns-core-modules";
// Load image from file
const documentsFolder = knownFolders.documents();
const imageFile = documentsFolder.getFile("photo.jpg");
const imageSource = ImageSource.fromFile(imageFile.path);
console.log(`Image size: ${imageSource.width}x${imageSource.height}`);
// Load from base64
const base64Data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAY...";
const base64Image = ImageSource.fromBase64(base64Data);
// Load from URL
async function loadImageFromUrl(url: string) {
try {
const imageSource = await ImageSource.fromUrl(url);
return imageSource;
} catch (error) {
console.error("Failed to load image:", error);
}
}
// Save image to file
const tempFolder = knownFolders.temp();
const outputPath = tempFolder.path + "/processed_image.png";
const success = imageSource.saveToFile(outputPath, "png", 90);
if (success) {
console.log("Image saved successfully");
}
// Convert to base64
const base64String = imageSource.toBase64String("jpeg", 80);
console.log("Base64 length:", base64String.length);
// Resize image
const resizedImage = imageSource.resize(300, {
maxWidth: 300,
maxHeight: 300,
aspectRatio: "aspectFit"
});Image asset representation for handling images from device photo library and camera.
/**
* Image asset for photo library and camera images
*/
class ImageAsset {
constructor(asset: any);
// Properties
readonly width: number;
readonly height: number;
readonly options: ImageAssetOptions;
// Image generation
getImage(options?: ImageAssetOptions): Promise<ImageSource>;
getImageData(): Promise<any>;
// Platform-specific access
readonly android: any; // Android asset
readonly ios: any; // iOS PHAsset
}
/**
* Image asset options for loading and processing
*/
interface ImageAssetOptions {
maxWidth?: number;
maxHeight?: number;
aspectRatio?: "aspectFill" | "aspectFit";
autoScaleFactor?: boolean;
keepAspectRatio?: boolean;
}Image Asset Usage Examples:
import { ImageAsset, ImageSource } from "tns-core-modules";
// Process image from camera/photo library
async function processImageAsset(asset: ImageAsset) {
const options: ImageAssetOptions = {
maxWidth: 800,
maxHeight: 600,
aspectRatio: "aspectFit",
autoScaleFactor: true
};
const imageSource = await asset.getImage(options);
console.log(`Processed image: ${imageSource.width}x${imageSource.height}`);
return imageSource;
}
// Get high-quality version
async function getFullResolution(asset: ImageAsset) {
const fullResImage = await asset.getImage({
autoScaleFactor: false
});
return fullResImage;
}High-performance image caching system for efficient memory management and network image loading.
/**
* Image cache for efficient image loading and memory management
*/
class Cache {
// Static instance
static getInstance(): Cache;
// Cache management
enableDownload(): void;
disableDownload(): void;
// Image operations
placeholder: ImageSource;
maxRequests: number;
// Request management
push(request: DownloadRequest): void;
remove(key: string): void;
clear(): void;
// Events
static downloadedEvent: "downloaded";
static downloadErrorEvent: "downloadError";
}
/**
* Download request for cached images
*/
interface DownloadRequest {
url: string;
key: string;
completed?: (image: ImageSource, key: string) => void;
error?: (error: DownloadError) => void;
}
/**
* Download error information
*/
interface DownloadError {
message: string;
statusCode?: number;
url: string;
}
/**
* Downloaded data result
*/
interface DownloadedData {
image: ImageSource;
key: string;
url: string;
}Image Cache Usage Examples:
import { Cache as ImageCache, DownloadRequest, ImageSource } from "tns-core-modules";
class ImageManager {
private cache: ImageCache;
constructor() {
this.cache = ImageCache.getInstance();
this.cache.enableDownload();
this.setupCacheEvents();
}
loadImage(url: string, key: string): Promise<ImageSource> {
return new Promise((resolve, reject) => {
const request: DownloadRequest = {
url: url,
key: key,
completed: (image, resultKey) => {
console.log(`Image loaded: ${resultKey}`);
resolve(image);
},
error: (error) => {
console.error(`Image load failed: ${error.message}`);
reject(new Error(error.message));
}
};
this.cache.push(request);
});
}
private setupCacheEvents(): void {
this.cache.on(ImageCache.downloadedEvent, (args) => {
console.log(`Downloaded: ${args.key}`);
});
this.cache.on(ImageCache.downloadErrorEvent, (args) => {
console.error(`Download error: ${args.error.message}`);
});
}
clearCache(): void {
this.cache.clear();
}
setPlaceholder(placeholder: ImageSource): void {
this.cache.placeholder = placeholder;
}
}
// Usage with ListView
class PhotoListManager {
private imageManager: ImageManager;
constructor() {
this.imageManager = new ImageManager();
// Set placeholder image
const placeholder = ImageSource.fromResource("placeholder");
this.imageManager.setPlaceholder(placeholder);
}
async loadPhotoList(photos: { id: string, url: string }[]) {
const loadPromises = photos.map(photo =>
this.imageManager.loadImage(photo.url, photo.id)
);
try {
const images = await Promise.all(loadPromises);
console.log(`Loaded ${images.length} images`);
return images;
} catch (error) {
console.error("Failed to load some images:", error);
}
}
}Utility functions for advanced image processing and manipulation.
/**
* Image processing utilities
*/
namespace ImageUtils {
// Format detection
function getImageFormat(source: ImageSource): "png" | "jpeg" | "gif" | "unknown";
function isValidImageData(data: any): boolean;
// Size calculations
function calculateAspectRatioSize(
originalWidth: number,
originalHeight: number,
maxWidth: number,
maxHeight: number
): { width: number, height: number };
// Memory management
function getImageMemorySize(source: ImageSource): number;
function optimizeForMemory(source: ImageSource, maxMemoryMB: number): ImageSource;
// Transformations
function rotate(source: ImageSource, degrees: number): ImageSource;
function flip(source: ImageSource, horizontal: boolean, vertical: boolean): ImageSource;
function crop(source: ImageSource, x: number, y: number, width: number, height: number): ImageSource;
}Complete Image Handling Example:
import { ImageSource, ImageAsset, Cache as ImageCache } from "tns-core-modules";
class PhotoEditor {
private cache: ImageCache;
constructor() {
this.cache = ImageCache.getInstance();
this.cache.enableDownload();
}
async processPhoto(asset: ImageAsset): Promise<ImageSource> {
// Get image from asset with optimization
const originalImage = await asset.getImage({
maxWidth: 1920,
maxHeight: 1080,
aspectRatio: "aspectFit"
});
console.log(`Original: ${originalImage.width}x${originalImage.height}`);
// Apply processing
const processedImage = this.applyFilters(originalImage);
// Save processed image
await this.saveProcessedImage(processedImage);
return processedImage;
}
private applyFilters(image: ImageSource): ImageSource {
// Resize for social media
const resized = image.resize(800, {
maxWidth: 800,
maxHeight: 600,
aspectRatio: "aspectFit"
});
return resized;
}
private async saveProcessedImage(image: ImageSource): Promise<string> {
const timestamp = Date.now();
const filename = `processed_${timestamp}.jpg`;
const outputPath = knownFolders.documents().path + "/" + filename;
const success = image.saveToFile(outputPath, "jpeg", 85);
if (success) {
console.log(`Saved to: ${outputPath}`);
return outputPath;
} else {
throw new Error("Failed to save processed image");
}
}
async loadAndCacheImages(urls: string[]): Promise<ImageSource[]> {
const promises = urls.map((url, index) => {
return new Promise<ImageSource>((resolve, reject) => {
this.cache.push({
url: url,
key: `image_${index}`,
completed: (image) => resolve(image),
error: (error) => reject(new Error(error.message))
});
});
});
return Promise.all(promises);
}
}Install with Tessl CLI
npx tessl i tessl/npm-tns-core-modules