or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

crop-service.mdimage-cropper-component.mdindex.mdload-image-service.mdutility-functions.md

utility-functions.mddocs/

0

# Utility Functions

1

2

Standalone utility functions for common image manipulation tasks including base64 conversion and canvas resizing operations.

3

4

## Capabilities

5

6

### Base64 to File Conversion

7

8

Convert base64 encoded image data to a Blob object for file operations.

9

10

```typescript { .api }

11

/**

12

* Convert base64 image string to Blob object

13

* @param base64Image - Base64 encoded image string with data URL prefix

14

* @returns Blob object containing the decoded image data

15

*/

16

function base64ToFile(base64Image: string): Blob;

17

```

18

19

**Usage Examples:**

20

21

```typescript

22

import { base64ToFile } from 'ngx-image-cropper';

23

24

// Convert base64 to blob for upload

25

const base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==';

26

const blob = base64ToFile(base64String);

27

28

console.log('Blob type:', blob.type); // 'image/png'

29

console.log('Blob size:', blob.size); // Size in bytes

30

31

// Use in FormData for upload

32

const formData = new FormData();

33

formData.append('image', blob, 'image.png');

34

35

// Upload to server

36

fetch('/upload', {

37

method: 'POST',

38

body: formData

39

});

40

41

// Create object URL for display

42

const objectUrl = URL.createObjectURL(blob);

43

const img = document.createElement('img');

44

img.src = objectUrl;

45

document.body.appendChild(img);

46

47

// Clean up object URL when done

48

URL.revokeObjectURL(objectUrl);

49

```

50

51

### Canvas Resizing

52

53

Resize canvas content using Hermite filter algorithm for high-quality image scaling.

54

55

```typescript { .api }

56

/**

57

* Resize canvas using Hermite filter algorithm

58

* @param canvas - HTMLCanvasElement to resize

59

* @param width - Target width in pixels

60

* @param height - Target height in pixels

61

*/

62

function resizeCanvas(canvas: HTMLCanvasElement, width: number, height: number): void;

63

```

64

65

**Usage Examples:**

66

67

```typescript

68

import { resizeCanvas } from 'ngx-image-cropper';

69

70

// Resize existing canvas content

71

const canvas = document.getElementById('myCanvas') as HTMLCanvasElement;

72

const ctx = canvas.getContext('2d');

73

74

// Draw some content on the canvas

75

ctx.fillStyle = 'red';

76

ctx.fillRect(0, 0, 100, 100);

77

78

console.log('Original size:', canvas.width, 'x', canvas.height);

79

80

// Resize the canvas content

81

resizeCanvas(canvas, 200, 150);

82

83

console.log('New size:', canvas.width, 'x', canvas.height); // 200 x 150

84

85

// The original content is now scaled to fit the new dimensions

86

```

87

88

### Advanced Usage Examples

89

90

```typescript

91

// Convert cropped image result to blob for storage

92

function saveCroppedImage(croppedEvent: ImageCroppedEvent) {

93

if (croppedEvent.base64) {

94

// Convert base64 result to blob

95

const blob = base64ToFile(croppedEvent.base64);

96

97

// Save to local storage as blob URL

98

const blobUrl = URL.createObjectURL(blob);

99

localStorage.setItem('croppedImage', blobUrl);

100

101

// Or download as file

102

const link = document.createElement('a');

103

link.href = blobUrl;

104

link.download = 'cropped-image.png';

105

link.click();

106

107

// Clean up

108

URL.revokeObjectURL(blobUrl);

109

}

110

}

111

112

// Resize canvas with quality control

113

function resizeCanvasWithQuality(

114

sourceCanvas: HTMLCanvasElement,

115

targetWidth: number,

116

targetHeight: number,

117

quality: 'fast' | 'high' = 'high'

118

) {

119

if (quality === 'high') {

120

// Use Hermite filter for high quality

121

resizeCanvas(sourceCanvas, targetWidth, targetHeight);

122

} else {

123

// Simple resize for speed

124

const ctx = sourceCanvas.getContext('2d');

125

if (ctx) {

126

const imageData = ctx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);

127

sourceCanvas.width = targetWidth;

128

sourceCanvas.height = targetHeight;

129

ctx.putImageData(imageData, 0, 0);

130

}

131

}

132

}

133

134

// Batch convert multiple base64 images

135

async function convertBase64Batch(base64Images: string[]): Promise<Blob[]> {

136

return base64Images.map(base64 => base64ToFile(base64));

137

}

138

139

// Create thumbnail from large canvas

140

function createThumbnail(

141

sourceCanvas: HTMLCanvasElement,

142

maxDimension: number = 150

143

): HTMLCanvasElement {

144

const ratio = Math.min(

145

maxDimension / sourceCanvas.width,

146

maxDimension / sourceCanvas.height

147

);

148

149

const thumbnailWidth = Math.round(sourceCanvas.width * ratio);

150

const thumbnailHeight = Math.round(sourceCanvas.height * ratio);

151

152

// Create new canvas for thumbnail

153

const thumbnailCanvas = document.createElement('canvas');

154

const ctx = thumbnailCanvas.getContext('2d');

155

156

if (ctx) {

157

// Copy original canvas content

158

thumbnailCanvas.width = sourceCanvas.width;

159

thumbnailCanvas.height = sourceCanvas.height;

160

ctx.drawImage(sourceCanvas, 0, 0);

161

162

// Resize to thumbnail size

163

resizeCanvas(thumbnailCanvas, thumbnailWidth, thumbnailHeight);

164

}

165

166

return thumbnailCanvas;

167

}

168

169

// Convert canvas to different formats

170

function canvasToMultipleFormats(canvas: HTMLCanvasElement) {

171

return {

172

// Convert to base64 in different formats

173

png: canvas.toDataURL('image/png'),

174

jpeg: canvas.toDataURL('image/jpeg', 0.9),

175

webp: canvas.toDataURL('image/webp', 0.8),

176

177

// Convert to blobs using utility function

178

pngBlob: base64ToFile(canvas.toDataURL('image/png')),

179

jpegBlob: base64ToFile(canvas.toDataURL('image/jpeg', 0.9)),

180

webpBlob: base64ToFile(canvas.toDataURL('image/webp', 0.8))

181

};

182

}

183

```

184

185

### Implementation Details

186

187

#### Base64 to File Algorithm

188

189

The `base64ToFile` function performs the following operations:

190

191

1. **Parse Data URL**: Extracts the MIME type and base64 data from the data URL string

192

2. **Decode Base64**: Converts the base64 string to binary data using `atob()`

193

3. **Create Array Buffer**: Builds an ArrayBuffer from the binary data

194

4. **Generate Blob**: Creates a Blob with the correct MIME type

195

196

#### Canvas Resize Algorithm

197

198

The `resizeCanvas` function uses the Hermite filter algorithm:

199

200

1. **Calculate Ratios**: Determines scaling ratios for width and height

201

2. **Hermite Filtering**: Applies mathematical filtering for smooth scaling

202

3. **Pixel Processing**: Processes each pixel with weighted contributions from source pixels

203

4. **Quality Preservation**: Maintains image quality during scaling operations

204

205

### Error Handling

206

207

```typescript

208

// Safe base64 conversion with error handling

209

function safeBase64ToFile(base64Image: string): Blob | null {

210

try {

211

return base64ToFile(base64Image);

212

} catch (error) {

213

console.error('Failed to convert base64 to file:', error);

214

return null;

215

}

216

}

217

218

// Safe canvas resize with validation

219

function safeResizeCanvas(

220

canvas: HTMLCanvasElement,

221

width: number,

222

height: number

223

): boolean {

224

try {

225

if (width <= 0 || height <= 0) {

226

console.error('Invalid dimensions for canvas resize');

227

return false;

228

}

229

230

if (!canvas.getContext('2d')) {

231

console.error('Canvas context not available');

232

return false;

233

}

234

235

resizeCanvas(canvas, width, height);

236

return true;

237

} catch (error) {

238

console.error('Failed to resize canvas:', error);

239

return false;

240

}

241

}

242

```