or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

auto-detection.mdcli-interface.mdconfiguration.mdcss-minification.mdhtml-minification.mdimage-processing.mdindex.mdjavascript-minification.md

image-processing.mddocs/

0

# Image Processing (Base64 Inlining)

1

2

CSS image optimization through base64 inlining to reduce HTTP requests and improve web performance by embedding small images directly in stylesheets.

3

4

## Capabilities

5

6

### Image Base64 Inlining Function

7

8

Converts CSS image references to base64 data URIs for reduced network requests.

9

10

```javascript { .api }

11

/**

12

* Converts CSS images to base64 inline format

13

* @param name - File path for directory context and resolution

14

* @param data - CSS data containing image URL references

15

* @param userOptions - Configuration options for image processing

16

* @returns Promise resolving to CSS with inlined base64 images

17

*/

18

function minify.img(name: string, data: string, userOptions?: MinifyOptions): Promise<string>;

19

20

interface MinifyOptions {

21

img?: {

22

maxSize?: number; // Maximum file size for inlining (bytes)

23

};

24

}

25

26

// Default configuration

27

const defaultImageOptions = {

28

maxSize: 102400 // 100KB (100 * 1024 bytes)

29

};

30

```

31

32

**Usage Examples:**

33

34

```javascript

35

import { minify } from "minify";

36

37

// Basic image inlining

38

const cssWithImages = `

39

.logo {

40

background-image: url('assets/logo.png');

41

}

42

.icon {

43

background: url('../icons/star.svg') center no-repeat;

44

}

45

`;

46

47

const inlined = await minify.img('/path/to/style.css', cssWithImages);

48

// Result: CSS with base64 data URIs replacing compatible image URLs

49

50

// Custom size limit

51

const customInlined = await minify.img('/path/to/style.css', cssWithImages, {

52

img: {

53

maxSize: 50000 // 50KB limit instead of default 100KB

54

}

55

});

56

57

// Integration with CSS minification

58

const optimized = await minify.css(cssWithImages, {

59

css: { type: 'clean-css' },

60

img: { maxSize: 25000 } // 25KB limit for inlining

61

});

62

```

63

64

## Image Processing Workflow

65

66

### File Resolution Process

67

68

1. **Parse CSS**: Extract `url()` references from CSS content

69

2. **Resolve Paths**: Convert relative URLs to absolute file paths using the `name` parameter context

70

3. **Check File Size**: Compare image file size against `maxSize` threshold

71

4. **Encode Eligible Images**: Convert qualifying images to base64 data URIs

72

5. **Replace URLs**: Substitute original URLs with inline data URIs

73

74

### Path Resolution

75

76

The `name` parameter provides directory context for resolving relative image paths:

77

78

```javascript { .api }

79

interface PathResolution {

80

baseDirectory: string; // Directory containing the CSS file

81

relativeDirectory: string; // Parent directory for relative resolution

82

}

83

84

// Path resolution examples:

85

// CSS file: /project/styles/main.css

86

// Base directory: /project/styles/

87

// Relative directory: /project/styles/../ = /project/

88

```

89

90

**Path Resolution Examples:**

91

92

```javascript

93

// CSS file path: /project/assets/css/styles.css

94

const cssContent = `

95

.header { background: url('images/header.jpg'); } // → /project/assets/css/images/header.jpg

96

.logo { background: url('../images/logo.png'); } // → /project/assets/images/logo.png

97

.icon { background: url('../../icons/star.svg'); } // → /project/icons/star.svg

98

`;

99

100

const result = await minify.img('/project/assets/css/styles.css', cssContent);

101

```

102

103

## Size Threshold Management

104

105

### Default Size Limits

106

107

Images are only inlined if they meet the size criteria:

108

109

```javascript { .api }

110

const ONE_KB = 1024; // 1 kilobyte in bytes

111

112

const defaultThresholds = {

113

maxSize: 100 * ONE_KB, // 102,400 bytes (100KB)

114

115

// Size considerations:

116

// - Small icons (< 5KB): Always inline for performance

117

// - Medium images (5-50KB): Inline for fewer requests

118

// - Large images (> 100KB): Keep as external files

119

};

120

```

121

122

### Custom Size Configuration

123

124

Configure size limits based on your performance requirements:

125

126

```javascript

127

// Conservative inlining (small images only)

128

const conservative = await minify.img(cssFile, cssData, {

129

img: { maxSize: 10000 } // 10KB limit

130

});

131

132

// Aggressive inlining (larger images)

133

const aggressive = await minify.img(cssFile, cssData, {

134

img: { maxSize: 500000 } // 500KB limit

135

});

136

137

// Disable inlining completely

138

const noInlining = await minify.img(cssFile, cssData, {

139

img: { maxSize: 0 } // No images will be inlined

140

});

141

```

142

143

## Supported Image Formats

144

145

Base64 inlining works with all common web image formats:

146

147

```javascript { .api }

148

interface SupportedFormats {

149

'image/png': string; // PNG images

150

'image/jpeg': string; // JPEG/JPG images

151

'image/gif': string; // GIF images

152

'image/svg+xml': string; // SVG vector graphics

153

'image/webp': string; // WebP images

154

'image/bmp': string; // Bitmap images

155

'image/ico': string; // Icon files

156

}

157

```

158

159

**Format-Specific Examples:**

160

161

```javascript

162

const multiFormatCSS = `

163

.png-icon { background: url('icon.png'); } // PNG support

164

.jpg-photo { background: url('photo.jpg'); } // JPEG support

165

.gif-animation { background: url('spinner.gif'); } // GIF support

166

.svg-vector { background: url('arrow.svg'); } // SVG support

167

.webp-modern { background: url('image.webp'); } // WebP support

168

`;

169

170

const inlined = await minify.img('/css/styles.css', multiFormatCSS);

171

// All compatible formats converted to appropriate data URIs

172

```

173

174

## Performance Considerations

175

176

### Benefits of Image Inlining

177

178

- **Reduced HTTP Requests**: Fewer network round trips

179

- **Faster Page Loading**: Eliminates image download delays

180

- **Better Caching**: Images cached with CSS

181

- **Simplified Deployment**: Fewer asset files to manage

182

183

### Drawbacks to Consider

184

185

- **Increased CSS Size**: Base64 encoding adds ~33% overhead

186

- **Cache Inefficiency**: Images re-downloaded with every CSS change

187

- **Memory Usage**: Base64 data uses more browser memory

188

- **Processing Overhead**: Encoding/decoding computational cost

189

190

### Best Practices

191

192

```javascript

193

// Optimal size thresholds for different use cases

194

const performanceOptimized = {

195

// Critical path icons and sprites

196

criticalAssets: { maxSize: 5000 }, // 5KB - inline critical icons

197

198

// General UI elements

199

uiElements: { maxSize: 25000 }, // 25KB - moderate inlining

200

201

// Background images and photos

202

backgroundImages: { maxSize: 0 }, // Don't inline large images

203

};

204

205

// Example usage

206

const criticalCSS = await minify.img(cssFile, criticalStyles, {

207

img: performanceOptimized.criticalAssets

208

});

209

```

210

211

## Integration with CSS Minification

212

213

Image inlining is automatically applied during CSS file minification:

214

215

```javascript

216

// Automatic image processing during CSS minification

217

const optimizedCSS = await minify('./styles.css', {

218

css: {

219

type: 'clean-css',

220

'clean-css': { level: 2 }

221

},

222

img: {

223

maxSize: 30000 // 30KB threshold for images

224

}

225

});

226

227

// The process:

228

// 1. CSS is minified using clean-css

229

// 2. Image inlining is automatically applied

230

// 3. Final result contains both optimizations

231

```

232

233

## Error Handling

234

235

Image processing handles various error conditions gracefully:

236

237

- **File Access Errors**: Missing image files are skipped with warnings

238

- **Path Resolution Errors**: Invalid paths are logged but don't break processing

239

- **Encoding Errors**: Corrupted images are skipped with error messages

240

- **Size Validation**: Files exceeding limits are left as external references

241

242

**Error Examples:**

243

244

```javascript

245

// Missing image file

246

const cssWithMissing = `.icon { background: url('missing.png'); }`;

247

const result = await minify.img('/css/style.css', cssWithMissing);

248

// Result: Original CSS unchanged, error logged

249

250

// Invalid path resolution

251

try {

252

await minify.img('', cssContent); // Empty name parameter

253

} catch (error) {

254

console.log(error); // AssertionError for missing name

255

}

256

257

// File size exceeded

258

const cssWithLargeImage = `.bg { background: url('large-photo.jpg'); }`;

259

const result = await minify.img('/css/style.css', cssWithLargeImage, {

260

img: { maxSize: 1000 } // 1KB limit

261

});

262

// Result: Large image URL preserved, not inlined

263

```