0
# Load Image Service
1
2
The LoadImageService manages image loading and transformation from various sources including files, URLs, and base64 strings, with automatic EXIF handling and format support.
3
4
## Capabilities
5
6
### Load Image Service Class
7
8
Injectable service for loading and transforming images from multiple sources.
9
10
```typescript { .api }
11
export class LoadImageService {
12
/**
13
* Load image from a File object
14
* @param file - File object containing image data
15
* @param options - Loading and transformation options
16
* @returns Promise resolving to LoadedImage with original and transformed data
17
*/
18
loadImageFile(file: File, options: LoadImageOptions): Promise<LoadedImage>;
19
20
/**
21
* Load image from a URL
22
* @param url - URL to fetch the image from
23
* @param options - Loading and transformation options
24
* @returns Promise resolving to LoadedImage with original and transformed data
25
*/
26
loadImageFromURL(url: string, options: LoadImageOptions): Promise<LoadedImage>;
27
28
/**
29
* Load image from base64 encoded string
30
* @param imageBase64 - Base64 encoded image string (with or without data URL prefix)
31
* @param options - Loading and transformation options
32
* @returns Promise resolving to LoadedImage with original and transformed data
33
*/
34
loadBase64Image(imageBase64: string, options: LoadImageOptions): Promise<LoadedImage>;
35
36
/**
37
* Transform an already loaded image with new options
38
* @param loadedImage - Partially loaded image data
39
* @param options - Transformation options to apply
40
* @param forceTransform - Force transformation even if no changes detected
41
* @returns Promise resolving to fully transformed LoadedImage
42
*/
43
transformLoadedImage(
44
loadedImage: Partial<LoadedImage>,
45
options: LoadImageOptions,
46
forceTransform?: boolean
47
): Promise<LoadedImage>;
48
}
49
```
50
51
**Usage Examples:**
52
53
```typescript
54
import { LoadImageService } from 'ngx-image-cropper';
55
56
const loadImageService = new LoadImageService();
57
58
// Load from file input
59
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
60
if (fileInput.files && fileInput.files[0]) {
61
const options: LoadImageOptions = {
62
format: 'png',
63
canvasRotation: 0,
64
aspectRatio: 16 / 9,
65
containWithinAspectRatio: false,
66
checkImageType: true
67
};
68
69
try {
70
const loadedImage = await loadImageService.loadImageFile(fileInput.files[0], options);
71
console.log('Original size:', loadedImage.original.size);
72
console.log('Transformed size:', loadedImage.transformed.size);
73
console.log('EXIF transform:', loadedImage.exifTransform);
74
} catch (error) {
75
console.error('Failed to load image:', error);
76
}
77
}
78
79
// Load from URL
80
try {
81
const loadedImage = await loadImageService.loadImageFromURL(
82
'https://example.com/image.jpg',
83
{ format: 'jpeg', checkImageType: true }
84
);
85
// Process loaded image
86
} catch (error) {
87
console.error('Failed to load image from URL:', error);
88
}
89
90
// Load from base64
91
const base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==';
92
try {
93
const loadedImage = await loadImageService.loadBase64Image(base64String, {
94
format: 'png',
95
canvasRotation: 90,
96
aspectRatio: 1
97
});
98
// Process loaded image
99
} catch (error) {
100
console.error('Failed to load base64 image:', error);
101
}
102
103
// Transform existing loaded image
104
const existingLoadedImage = { /* partial loaded image */ };
105
const newOptions: LoadImageOptions = {
106
canvasRotation: 180,
107
containWithinAspectRatio: true,
108
aspectRatio: 4 / 3
109
};
110
111
try {
112
const transformedImage = await loadImageService.transformLoadedImage(
113
existingLoadedImage,
114
newOptions,
115
true // Force transformation
116
);
117
// Use transformed image
118
} catch (error) {
119
console.error('Failed to transform image:', error);
120
}
121
```
122
123
### Load Image Options
124
125
Configuration options for image loading and transformation.
126
127
```typescript { .api }
128
interface LoadImageOptions {
129
/** Output format for transformed images */
130
format?: OutputFormat;
131
/** Canvas rotation angle in degrees (0, 90, 180, 270) */
132
canvasRotation?: number;
133
/** Target aspect ratio for containment */
134
aspectRatio?: number;
135
/** Contain image within aspect ratio bounds */
136
containWithinAspectRatio?: boolean;
137
/** Validate image file type before loading */
138
checkImageType?: boolean;
139
}
140
```
141
142
### Loaded Image Structure
143
144
Data structure containing original and transformed image information.
145
146
```typescript { .api }
147
interface LoadedImage {
148
/** Original image data as loaded */
149
original: {
150
/** Object URL for the original image */
151
objectUrl: string;
152
/** HTMLImageElement containing the original image */
153
image: HTMLImageElement;
154
/** Dimensions of the original image */
155
size: Dimensions;
156
};
157
/** Transformed image data after processing */
158
transformed: {
159
/** Object URL for the transformed image */
160
objectUrl: string;
161
/** HTMLImageElement containing the transformed image */
162
image: HTMLImageElement;
163
/** Dimensions of the transformed image */
164
size: Dimensions;
165
};
166
/** EXIF transformation data extracted from image metadata */
167
exifTransform: ExifTransform;
168
}
169
```
170
171
### EXIF Transform
172
173
EXIF metadata transformations automatically applied during image loading.
174
175
```typescript { .api }
176
interface ExifTransform {
177
/** Rotation angle from EXIF data */
178
rotate: number;
179
/** Horizontal flip from EXIF data */
180
flip: boolean;
181
}
182
```
183
184
### Supported Image Formats
185
186
The service supports loading the following image formats:
187
188
```typescript { .api }
189
// Supported MIME types for image validation
190
type SupportedImageTypes =
191
| 'image/png'
192
| 'image/jpg'
193
| 'image/jpeg'
194
| 'image/heic'
195
| 'image/bmp'
196
| 'image/gif'
197
| 'image/tiff'
198
| 'image/svg+xml'
199
| 'image/webp'
200
| 'image/x-icon'
201
| 'image/vnd.microsoft.icon';
202
```
203
204
### Advanced Usage Examples
205
206
```typescript
207
// Loading with comprehensive options
208
const comprehensiveOptions: LoadImageOptions = {
209
format: 'jpeg',
210
canvasRotation: 90,
211
aspectRatio: 16 / 9,
212
containWithinAspectRatio: true,
213
checkImageType: true
214
};
215
216
// Load and handle different scenarios
217
async function loadImageWithErrorHandling(file: File) {
218
try {
219
const loadedImage = await loadImageService.loadImageFile(file, comprehensiveOptions);
220
221
// Check if transformation was applied
222
const wasTransformed = loadedImage.original.objectUrl !== loadedImage.transformed.objectUrl;
223
console.log('Image was transformed:', wasTransformed);
224
225
// Handle EXIF data
226
if (loadedImage.exifTransform.rotate !== 0) {
227
console.log('Image had EXIF rotation:', loadedImage.exifTransform.rotate);
228
}
229
230
if (loadedImage.exifTransform.flip) {
231
console.log('Image had EXIF flip transformation');
232
}
233
234
return loadedImage;
235
} catch (error) {
236
if (error instanceof Error) {
237
if (error.message === 'Invalid image type') {
238
console.error('Unsupported image format');
239
} else if (error.message === 'No image loaded') {
240
console.error('Image failed to load');
241
} else {
242
console.error('Unknown error:', error.message);
243
}
244
}
245
throw error;
246
}
247
}
248
249
// Transform image with different canvas rotations
250
async function rotateImage(loadedImage: LoadedImage, rotation: number) {
251
const rotationOptions: LoadImageOptions = {
252
...comprehensiveOptions,
253
canvasRotation: rotation
254
};
255
256
return await loadImageService.transformLoadedImage(
257
loadedImage,
258
rotationOptions,
259
true
260
);
261
}
262
263
// Load SVG with special handling
264
async function loadSvgImage(svgFile: File) {
265
const svgOptions: LoadImageOptions = {
266
format: 'png', // Convert SVG to PNG
267
checkImageType: true
268
};
269
270
try {
271
const loadedImage = await loadImageService.loadImageFile(svgFile, svgOptions);
272
// SVG images may have special size handling
273
console.log('SVG loaded and converted to:', loadedImage.transformed.size);
274
return loadedImage;
275
} catch (error) {
276
if (error instanceof Error && error.message.includes('Failed to load SVG')) {
277
console.error('SVG must have width + height or viewBox definition');
278
}
279
throw error;
280
}
281
}
282
```
283
284
### Error Handling
285
286
The service throws specific errors for different failure scenarios:
287
288
- `'Invalid image type'` - When checkImageType is true and file type is not supported
289
- `'No image loaded'` - When image fails to load or is corrupted
290
- `'Failed to parse SVG image'` - When SVG structure is invalid
291
- `'Failed to load SVG image. SVG must have width + height or viewBox definition.'` - When SVG lacks size information
292
- `'Failed to get Blob for transformed image.'` - When canvas transformation fails