0
# Image Handling
1
2
Comprehensive image loading, manipulation, and caching capabilities for mobile applications. The image handling system supports multiple image sources, format conversion, and efficient memory management.
3
4
## Capabilities
5
6
### Image Source
7
8
Core image representation class providing image loading and manipulation functionality.
9
10
```typescript { .api }
11
/**
12
* Image source class for image loading and manipulation
13
*/
14
class ImageSource {
15
// Static factory methods
16
static fromFile(path: string): ImageSource;
17
static fromData(data: any): ImageSource;
18
static fromBase64(source: string): ImageSource;
19
static fromResource(name: string): ImageSource;
20
static fromUrl(url: string): Promise<ImageSource>;
21
static fromAsset(asset: ImageAsset): Promise<ImageSource>;
22
23
// Properties
24
readonly width: number;
25
readonly height: number;
26
readonly rotationAngle: number;
27
28
// File operations
29
saveToFile(path: string, format: "png" | "jpeg", quality?: number): boolean;
30
toBase64String(format: "png" | "jpeg", quality?: number): string;
31
32
// Image manipulation
33
resize(maxSize: number, options?: ResizeOptions): ImageSource;
34
35
// Platform-specific native access
36
readonly android: any; // Android Bitmap
37
readonly ios: any; // iOS UIImage
38
}
39
40
/**
41
* Image resize options
42
*/
43
interface ResizeOptions {
44
maxWidth?: number;
45
maxHeight?: number;
46
aspectRatio?: "aspectFill" | "aspectFit";
47
quality?: number;
48
}
49
```
50
51
**Usage Examples:**
52
53
```typescript
54
import { ImageSource, knownFolders } from "tns-core-modules";
55
56
// Load image from file
57
const documentsFolder = knownFolders.documents();
58
const imageFile = documentsFolder.getFile("photo.jpg");
59
const imageSource = ImageSource.fromFile(imageFile.path);
60
61
console.log(`Image size: ${imageSource.width}x${imageSource.height}`);
62
63
// Load from base64
64
const base64Data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAY...";
65
const base64Image = ImageSource.fromBase64(base64Data);
66
67
// Load from URL
68
async function loadImageFromUrl(url: string) {
69
try {
70
const imageSource = await ImageSource.fromUrl(url);
71
return imageSource;
72
} catch (error) {
73
console.error("Failed to load image:", error);
74
}
75
}
76
77
// Save image to file
78
const tempFolder = knownFolders.temp();
79
const outputPath = tempFolder.path + "/processed_image.png";
80
const success = imageSource.saveToFile(outputPath, "png", 90);
81
82
if (success) {
83
console.log("Image saved successfully");
84
}
85
86
// Convert to base64
87
const base64String = imageSource.toBase64String("jpeg", 80);
88
console.log("Base64 length:", base64String.length);
89
90
// Resize image
91
const resizedImage = imageSource.resize(300, {
92
maxWidth: 300,
93
maxHeight: 300,
94
aspectRatio: "aspectFit"
95
});
96
```
97
98
### Image Asset
99
100
Image asset representation for handling images from device photo library and camera.
101
102
```typescript { .api }
103
/**
104
* Image asset for photo library and camera images
105
*/
106
class ImageAsset {
107
constructor(asset: any);
108
109
// Properties
110
readonly width: number;
111
readonly height: number;
112
readonly options: ImageAssetOptions;
113
114
// Image generation
115
getImage(options?: ImageAssetOptions): Promise<ImageSource>;
116
getImageData(): Promise<any>;
117
118
// Platform-specific access
119
readonly android: any; // Android asset
120
readonly ios: any; // iOS PHAsset
121
}
122
123
/**
124
* Image asset options for loading and processing
125
*/
126
interface ImageAssetOptions {
127
maxWidth?: number;
128
maxHeight?: number;
129
aspectRatio?: "aspectFill" | "aspectFit";
130
autoScaleFactor?: boolean;
131
keepAspectRatio?: boolean;
132
}
133
```
134
135
**Image Asset Usage Examples:**
136
137
```typescript
138
import { ImageAsset, ImageSource } from "tns-core-modules";
139
140
// Process image from camera/photo library
141
async function processImageAsset(asset: ImageAsset) {
142
const options: ImageAssetOptions = {
143
maxWidth: 800,
144
maxHeight: 600,
145
aspectRatio: "aspectFit",
146
autoScaleFactor: true
147
};
148
149
const imageSource = await asset.getImage(options);
150
console.log(`Processed image: ${imageSource.width}x${imageSource.height}`);
151
152
return imageSource;
153
}
154
155
// Get high-quality version
156
async function getFullResolution(asset: ImageAsset) {
157
const fullResImage = await asset.getImage({
158
autoScaleFactor: false
159
});
160
161
return fullResImage;
162
}
163
```
164
165
### Image Cache
166
167
High-performance image caching system for efficient memory management and network image loading.
168
169
```typescript { .api }
170
/**
171
* Image cache for efficient image loading and memory management
172
*/
173
class Cache {
174
// Static instance
175
static getInstance(): Cache;
176
177
// Cache management
178
enableDownload(): void;
179
disableDownload(): void;
180
181
// Image operations
182
placeholder: ImageSource;
183
maxRequests: number;
184
185
// Request management
186
push(request: DownloadRequest): void;
187
remove(key: string): void;
188
clear(): void;
189
190
// Events
191
static downloadedEvent: "downloaded";
192
static downloadErrorEvent: "downloadError";
193
}
194
195
/**
196
* Download request for cached images
197
*/
198
interface DownloadRequest {
199
url: string;
200
key: string;
201
completed?: (image: ImageSource, key: string) => void;
202
error?: (error: DownloadError) => void;
203
}
204
205
/**
206
* Download error information
207
*/
208
interface DownloadError {
209
message: string;
210
statusCode?: number;
211
url: string;
212
}
213
214
/**
215
* Downloaded data result
216
*/
217
interface DownloadedData {
218
image: ImageSource;
219
key: string;
220
url: string;
221
}
222
```
223
224
**Image Cache Usage Examples:**
225
226
```typescript
227
import { Cache as ImageCache, DownloadRequest, ImageSource } from "tns-core-modules";
228
229
class ImageManager {
230
private cache: ImageCache;
231
232
constructor() {
233
this.cache = ImageCache.getInstance();
234
this.cache.enableDownload();
235
this.setupCacheEvents();
236
}
237
238
loadImage(url: string, key: string): Promise<ImageSource> {
239
return new Promise((resolve, reject) => {
240
const request: DownloadRequest = {
241
url: url,
242
key: key,
243
completed: (image, resultKey) => {
244
console.log(`Image loaded: ${resultKey}`);
245
resolve(image);
246
},
247
error: (error) => {
248
console.error(`Image load failed: ${error.message}`);
249
reject(new Error(error.message));
250
}
251
};
252
253
this.cache.push(request);
254
});
255
}
256
257
private setupCacheEvents(): void {
258
this.cache.on(ImageCache.downloadedEvent, (args) => {
259
console.log(`Downloaded: ${args.key}`);
260
});
261
262
this.cache.on(ImageCache.downloadErrorEvent, (args) => {
263
console.error(`Download error: ${args.error.message}`);
264
});
265
}
266
267
clearCache(): void {
268
this.cache.clear();
269
}
270
271
setPlaceholder(placeholder: ImageSource): void {
272
this.cache.placeholder = placeholder;
273
}
274
}
275
276
// Usage with ListView
277
class PhotoListManager {
278
private imageManager: ImageManager;
279
280
constructor() {
281
this.imageManager = new ImageManager();
282
283
// Set placeholder image
284
const placeholder = ImageSource.fromResource("placeholder");
285
this.imageManager.setPlaceholder(placeholder);
286
}
287
288
async loadPhotoList(photos: { id: string, url: string }[]) {
289
const loadPromises = photos.map(photo =>
290
this.imageManager.loadImage(photo.url, photo.id)
291
);
292
293
try {
294
const images = await Promise.all(loadPromises);
295
console.log(`Loaded ${images.length} images`);
296
return images;
297
} catch (error) {
298
console.error("Failed to load some images:", error);
299
}
300
}
301
}
302
```
303
304
### Image Processing Utilities
305
306
Utility functions for advanced image processing and manipulation.
307
308
```typescript { .api }
309
/**
310
* Image processing utilities
311
*/
312
namespace ImageUtils {
313
// Format detection
314
function getImageFormat(source: ImageSource): "png" | "jpeg" | "gif" | "unknown";
315
function isValidImageData(data: any): boolean;
316
317
// Size calculations
318
function calculateAspectRatioSize(
319
originalWidth: number,
320
originalHeight: number,
321
maxWidth: number,
322
maxHeight: number
323
): { width: number, height: number };
324
325
// Memory management
326
function getImageMemorySize(source: ImageSource): number;
327
function optimizeForMemory(source: ImageSource, maxMemoryMB: number): ImageSource;
328
329
// Transformations
330
function rotate(source: ImageSource, degrees: number): ImageSource;
331
function flip(source: ImageSource, horizontal: boolean, vertical: boolean): ImageSource;
332
function crop(source: ImageSource, x: number, y: number, width: number, height: number): ImageSource;
333
}
334
```
335
336
**Complete Image Handling Example:**
337
338
```typescript
339
import { ImageSource, ImageAsset, Cache as ImageCache } from "tns-core-modules";
340
341
class PhotoEditor {
342
private cache: ImageCache;
343
344
constructor() {
345
this.cache = ImageCache.getInstance();
346
this.cache.enableDownload();
347
}
348
349
async processPhoto(asset: ImageAsset): Promise<ImageSource> {
350
// Get image from asset with optimization
351
const originalImage = await asset.getImage({
352
maxWidth: 1920,
353
maxHeight: 1080,
354
aspectRatio: "aspectFit"
355
});
356
357
console.log(`Original: ${originalImage.width}x${originalImage.height}`);
358
359
// Apply processing
360
const processedImage = this.applyFilters(originalImage);
361
362
// Save processed image
363
await this.saveProcessedImage(processedImage);
364
365
return processedImage;
366
}
367
368
private applyFilters(image: ImageSource): ImageSource {
369
// Resize for social media
370
const resized = image.resize(800, {
371
maxWidth: 800,
372
maxHeight: 600,
373
aspectRatio: "aspectFit"
374
});
375
376
return resized;
377
}
378
379
private async saveProcessedImage(image: ImageSource): Promise<string> {
380
const timestamp = Date.now();
381
const filename = `processed_${timestamp}.jpg`;
382
const outputPath = knownFolders.documents().path + "/" + filename;
383
384
const success = image.saveToFile(outputPath, "jpeg", 85);
385
386
if (success) {
387
console.log(`Saved to: ${outputPath}`);
388
return outputPath;
389
} else {
390
throw new Error("Failed to save processed image");
391
}
392
}
393
394
async loadAndCacheImages(urls: string[]): Promise<ImageSource[]> {
395
const promises = urls.map((url, index) => {
396
return new Promise<ImageSource>((resolve, reject) => {
397
this.cache.push({
398
url: url,
399
key: `image_${index}`,
400
completed: (image) => resolve(image),
401
error: (error) => reject(new Error(error.message))
402
});
403
});
404
});
405
406
return Promise.all(promises);
407
}
408
}
409
```