0
# Resizing and Geometry
1
2
Sharp provides comprehensive image resizing and geometric transformation capabilities with multiple fit strategies, interpolation methods, and precision controls.
3
4
## Capabilities
5
6
### Image Resizing
7
8
Resize images with various fit strategies and quality controls.
9
10
```javascript { .api }
11
/**
12
* Resize image to specified dimensions
13
* @param widthOrOptions - Target width or ResizeOptions object
14
* @param height - Target height in pixels (optional)
15
* @param options - Additional resize options (optional)
16
* @returns Sharp instance for chaining
17
*/
18
resize(widthOrOptions?: number | ResizeOptions, height?: number, options?: ResizeOptions): Sharp;
19
20
interface ResizeOptions {
21
/** Target width (alternative to first parameter) */
22
width?: number;
23
/** Target height (alternative to second parameter) */
24
height?: number;
25
/** How image should fit both dimensions */
26
fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside';
27
/** Position/gravity when using cover or contain */
28
position?: number | string;
29
/** Background color for contain mode */
30
background?: string | RGBA;
31
/** Interpolation kernel for image reduction */
32
kernel?: 'nearest' | 'cubic' | 'mitchell' | 'lanczos2' | 'lanczos3' | 'mks2013' | 'mks2021';
33
/** Don't enlarge if smaller than target */
34
withoutEnlargement?: boolean;
35
/** Don't reduce if larger than target */
36
withoutReduction?: boolean;
37
/** Use shrink-on-load optimization */
38
fastShrinkOnLoad?: boolean;
39
}
40
```
41
42
**Fit Strategies:**
43
- `cover` - Crop to cover both dimensions (default)
44
- `contain` - Embed within both dimensions
45
- `fill` - Stretch ignoring aspect ratio
46
- `inside` - Fit within dimensions preserving aspect ratio
47
- `outside` - Ensure dimensions are exceeded preserving aspect ratio
48
49
**Usage Examples:**
50
51
```javascript
52
// Basic resize
53
await sharp('input.jpg')
54
.resize(800, 600)
55
.toFile('output.jpg');
56
57
// Resize with fit strategy
58
await sharp('input.jpg')
59
.resize({
60
width: 800,
61
height: 600,
62
fit: 'contain',
63
background: 'white'
64
})
65
.toFile('contain.jpg');
66
67
// Resize maintaining aspect ratio
68
await sharp('input.jpg')
69
.resize({ width: 800, fit: 'inside' })
70
.toFile('proportional.jpg');
71
72
// High-quality resize
73
await sharp('input.jpg')
74
.resize(400, 300, {
75
kernel: 'lanczos3',
76
withoutEnlargement: true
77
})
78
.toFile('hq-resize.jpg');
79
```
80
81
### Region Extraction
82
83
Extract/crop specific regions from images.
84
85
```javascript { .api }
86
/**
87
* Extract region from image (crop operation)
88
* @param region - Region coordinates and dimensions
89
* @returns Sharp instance for chaining
90
*/
91
extract(region: Region): Sharp;
92
93
interface Region {
94
/** Zero-indexed offset from left edge */
95
left: number;
96
/** Zero-indexed offset from top edge */
97
top: number;
98
/** Width of extracted region */
99
width: number;
100
/** Height of extracted region */
101
height: number;
102
}
103
```
104
105
**Usage Examples:**
106
107
```javascript
108
// Extract region
109
await sharp('input.jpg')
110
.extract({ left: 100, top: 50, width: 400, height: 300 })
111
.toFile('cropped.jpg');
112
113
// Pre-resize extraction (crop then resize)
114
await sharp('input.jpg')
115
.extract({ left: 0, top: 0, width: 800, height: 800 })
116
.resize(400, 400)
117
.toFile('crop-then-resize.jpg');
118
119
// Post-resize extraction (resize then crop)
120
await sharp('input.jpg')
121
.resize(1000, 1000)
122
.extract({ left: 250, top: 250, width: 500, height: 500 })
123
.toFile('resize-then-crop.jpg');
124
```
125
126
### Image Extension
127
128
Extend/pad image edges with background or derived pixels.
129
130
```javascript { .api }
131
/**
132
* Extend image edges with padding
133
* @param extend - Padding amount or detailed options
134
* @returns Sharp instance for chaining
135
*/
136
extend(extend: number | ExtendOptions): Sharp;
137
138
interface ExtendOptions {
139
/** Padding for top edge */
140
top?: number;
141
/** Padding for left edge */
142
left?: number;
143
/** Padding for bottom edge */
144
bottom?: number;
145
/** Padding for right edge */
146
right?: number;
147
/** Background color for padding */
148
background?: string | RGBA;
149
/** How extension is done */
150
extendWith?: 'background' | 'copy' | 'repeat' | 'mirror';
151
}
152
```
153
154
**Extension Methods:**
155
- `background` - Use background color (default)
156
- `copy` - Copy edge pixels
157
- `repeat` - Repeat edge pixels
158
- `mirror` - Mirror edge pixels
159
160
**Usage Examples:**
161
162
```javascript
163
// Uniform padding
164
await sharp('input.jpg')
165
.extend(50)
166
.toFile('padded.jpg');
167
168
// Different padding per edge
169
await sharp('input.jpg')
170
.extend({
171
top: 20,
172
bottom: 20,
173
left: 50,
174
right: 50,
175
background: '#ff0000'
176
})
177
.toFile('custom-padding.jpg');
178
179
// Mirror extension
180
await sharp('input.jpg')
181
.extend({
182
top: 100,
183
bottom: 100,
184
extendWith: 'mirror'
185
})
186
.toFile('mirrored.jpg');
187
```
188
189
### Edge Trimming
190
191
Remove edges with similar colors to background.
192
193
```javascript { .api }
194
/**
195
* Trim similar-colored edges from image
196
* @param options - Trimming options
197
* @returns Sharp instance for chaining
198
*/
199
trim(options?: TrimOptions): Sharp;
200
201
interface TrimOptions {
202
/** Background color (defaults to top-left pixel) */
203
background?: string | RGBA;
204
/** Color difference threshold (0-255) */
205
threshold?: number;
206
/** Optimize for line art vs photographic content */
207
lineArt?: boolean;
208
}
209
```
210
211
**Usage Examples:**
212
213
```javascript
214
// Basic trim (uses top-left pixel as background)
215
await sharp('input.png')
216
.trim()
217
.toFile('trimmed.png');
218
219
// Trim with specific background
220
await sharp('input.png')
221
.trim({
222
background: 'white',
223
threshold: 20
224
})
225
.toFile('white-trimmed.png');
226
227
// Trim line art
228
await sharp('vector-input.png')
229
.trim({
230
lineArt: true,
231
threshold: 5
232
})
233
.toFile('line-art-trimmed.png');
234
```
235
236
## Position and Gravity Constants
237
238
Sharp provides constants for positioning and gravity options.
239
240
```javascript { .api }
241
// Available via sharp.gravity
242
interface GravityEnum {
243
north: number;
244
northeast: number;
245
east: number;
246
southeast: number;
247
south: number;
248
southwest: number;
249
west: number;
250
northwest: number;
251
center: number;
252
centre: number;
253
}
254
255
// Available via sharp.strategy
256
interface StrategyEnum {
257
entropy: number;
258
attention: number;
259
}
260
261
// Available via sharp.kernel
262
interface KernelEnum {
263
nearest: 'nearest';
264
cubic: 'cubic';
265
mitchell: 'mitchell';
266
lanczos2: 'lanczos2';
267
lanczos3: 'lanczos3';
268
mks2013: 'mks2013';
269
mks2021: 'mks2021';
270
}
271
272
// Available via sharp.fit
273
interface FitEnum {
274
contain: 'contain';
275
cover: 'cover';
276
fill: 'fill';
277
inside: 'inside';
278
outside: 'outside';
279
}
280
```
281
282
**Usage Examples:**
283
284
```javascript
285
// Using gravity constants
286
await sharp('input.jpg')
287
.resize({
288
width: 400,
289
height: 400,
290
fit: 'cover',
291
position: sharp.gravity.northeast
292
})
293
.toFile('gravity-crop.jpg');
294
295
// Using strategy for smart cropping
296
await sharp('input.jpg')
297
.resize({
298
width: 400,
299
height: 400,
300
fit: 'cover',
301
position: sharp.strategy.attention
302
})
303
.toFile('smart-crop.jpg');
304
305
// Using interpolation kernel
306
await sharp('input.jpg')
307
.resize(800, 600, {
308
kernel: sharp.kernel.lanczos3
309
})
310
.toFile('hq-resize.jpg');
311
```
312
313
## Advanced Resize Patterns
314
315
**Batch Processing:**
316
317
```javascript
318
const sizes = [
319
{ width: 200, suffix: '-thumb' },
320
{ width: 400, suffix: '-small' },
321
{ width: 800, suffix: '-medium' },
322
{ width: 1200, suffix: '-large' }
323
];
324
325
const image = sharp('input.jpg');
326
327
await Promise.all(
328
sizes.map(size =>
329
image
330
.clone()
331
.resize({ width: size.width, fit: 'inside' })
332
.jpeg({ quality: 90 })
333
.toFile(`output${size.suffix}.jpg`)
334
)
335
);
336
```
337
338
**Responsive Images:**
339
340
```javascript
341
// Generate multiple sizes for responsive images
342
const generateResponsive = async (input, basename) => {
343
const image = sharp(input);
344
const metadata = await image.metadata();
345
346
const sizes = [480, 768, 1024, 1200];
347
348
return Promise.all(
349
sizes.map(width =>
350
image
351
.clone()
352
.resize({
353
width: Math.min(width, metadata.width),
354
fit: 'inside',
355
withoutEnlargement: true
356
})
357
.webp({ quality: 85 })
358
.toFile(`${basename}-${width}w.webp`)
359
)
360
);
361
};
362
```