/
imageTransforms.ts
463 lines (437 loc) · 12.6 KB
/
imageTransforms.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import { BorderObject, ImageTransform, StringOverlayStyle } from './imageTransformTypes'
import {
includes,
invariantImage as invariant,
isNumber,
shouldBeOneOf,
startsWith,
} from '../utils'
// http://cloudinary.com/documentation/image_transformation_reference#format_parameter
const formatOptions = [
'jpg',
'jpe',
'jpeg',
'jpc',
'jp2',
'j2k',
'wdp',
'jxr',
'hdp',
'png',
'gif',
'webp',
'bmp',
'tif',
'tiff',
'ico',
'pdf',
'ps',
'ept',
'eps',
'eps3',
'psd',
'svg',
'ai',
'djvu',
'flif',
]
// http://cloudinary.com/documentation/image_transformation_reference#crop_parameter
const cropOptions = [
'scale',
'fit',
'limit',
'mfit',
'fill',
'lfill',
'pad',
'lpad',
'mpad',
'crop',
'thumb',
'imagga_crop',
'imagga_scale',
]
// http://cloudinary.com/documentation/image_transformation_reference#gravity_parameter
const gravityOptions = [
'north_west',
'north',
'north_east',
'west',
'center',
'east',
'south_west',
'south',
'south_east',
'xy_center',
'face',
'face:center',
'face:auto',
'faces',
'faces:center',
'faces:auto',
'body',
'body:face',
'ocr_text',
'adv_face',
'adv_faces',
'adv_eyes',
'custom',
'custom:face',
'custom:faces',
'custom:adv_face',
'custom:adv_faces',
]
// http://cloudinary.com/documentation/image_transformation_reference#quality_parameter
const qualityOptions = ['auto', 'auto:best', 'auto:good', 'auto:eco', 'auto:low', 'jpegmini']
// http://cloudinary.com/documentation/image_transformation_reference#angle_parameter
const angleOptions = ['auto_right', 'auto_left', 'ignore', 'vflip', 'hflip']
// http://cloudinary.com/documentation/image_transformation_reference#background_parameter
const backgroundOptions = [
'auto:border',
'auto:predominant',
'auto:border_contrast',
'auto:predominant_contrast',
]
// http://cloudinary.com/documentation/image_transformation_reference#color_parameter
// A color name or rgb: followed by an rgb[a] or rrggbb[aa] hex value
const colorRegex = /^(?:[a-z]+$|rgb:(?:[0-9a-f]{3,4}$|[0-9a-f]{6}$|[0-9a-f]{8}$))/i
// http://cloudinary.com/documentation/image_transformation_reference#color_space_parameter
const colorSpaceOptions = ['srgb', 'tinysrgb', 'no_cmyk']
const flagOptions = [
'any_format',
'attachment',
'apng',
'awebp',
'clip',
'clip_evenodd',
'cutter',
'force_strip',
'ignore_aspect_ratio',
'immutable_cache',
'keep_attribution',
'keep_iptc',
'layer_apply',
'lossy',
'no_overflow',
'preserve_transparency',
'png8',
'png24',
'png32',
'progressive',
'progressive:semi',
'progressive:steep',
'progressive:none',
'rasterize',
'region_relative',
'relative',
'strip_profile',
'text_no_trim',
'tiff8_lwz',
'tiled',
]
// Undefined or null values are filtered before validation
type ImgOpt = Required<ImageTransform>
type Validators = { [Key in keyof ImgOpt]: (value: ImgOpt[Key]) => void } & {
borderObjectColor: (value: BorderObject) => void
} & { textCaptionStyles: (value: StringOverlayStyle) => void }
const validate: Validators = {
width: (value: ImgOpt['width']) =>
invariant(
isNumber(value) || (typeof value === 'string' && value.match(/^auto(?:$|(?::.+))/)),
'width',
value,
`should be a number, 'auto', or a string starting with 'auto:'`,
),
height: (value: ImgOpt['height']) =>
invariant(isNumber(value), 'height', value, 'should be a number'),
crop: (value: ImgOpt['crop']) =>
invariant(value && includes(value, cropOptions), 'crop', value, shouldBeOneOf(cropOptions)),
aspectRatio: (value: ImgOpt['aspectRatio']) =>
invariant(
isNumber(value) || (typeof value === 'string' && value.match(/^\d+:\d+$/)),
'aspectRatio',
value,
'should be a number or have the form x:y',
),
gravity: (value: ImgOpt['gravity']) =>
invariant(
includes(value, gravityOptions) || value === 'auto' || startsWith('auto:', value),
'gravity',
value,
`${shouldBeOneOf(gravityOptions)}, 'auto', or a string starting with 'auto:'`,
),
zoom: (value: ImgOpt['zoom']) => invariant(isNumber(value), 'zoom', value, 'should be a number'),
x: (value: ImgOpt['x']) => invariant(isNumber(value), 'x', value, 'should be a number'),
y: (value: ImgOpt['y']) => invariant(isNumber(value), 'y', value, 'should be a number'),
format: (value: ImgOpt['fetchFormat']) =>
invariant(
includes(value, ['auto', ...formatOptions]),
'fetchFormat',
value,
`${shouldBeOneOf(['auto', ...formatOptions])} or 'auto'`,
),
fetchFormat(value: ImgOpt['fetchFormat']) {
this.format(value)
},
quality: (value: ImgOpt['quality']) =>
invariant(
(isNumber(value) && 1 <= +value && +value <= 100) ||
(typeof value === 'string' &&
(value.match(/^\d+:\d+$/) || includes(value, qualityOptions))),
'quality',
value,
`${shouldBeOneOf(formatOptions)}, a number between 1 and 100, or have the form x:y`,
),
radius: (value: ImgOpt['radius']) =>
invariant(
isNumber(value) ||
value === 'max' ||
(typeof value === 'string' && value.match(/^\d+(?::\d+){0,3}$/)),
'radius',
value,
`should be a number, 'max' or have the form x[:y[:z[:u]]]`,
),
angle: (value: ImgOpt['angle']) =>
invariant(
isNumber(value) || (typeof value === 'string' && includes(value, angleOptions)),
'angle',
value,
`${shouldBeOneOf(angleOptions)} or a number`,
),
effect: () => {
// No validation
},
opacity: (value: ImgOpt['opacity']) =>
invariant(
isNumber(value) && 0 <= +value && +value <= 100,
'opacity',
value,
'should be a number between 0 and 100',
),
border: (value: ImgOpt['border']) =>
invariant(
typeof value === 'string' &&
value.match(
new RegExp(`^\\d+px_solid_${colorRegex.toString().replace(/[/^i]/g, '')}$`, 'i'),
),
'border',
value,
`should be an object with 'width' & 'color' or a string of the form 'width_style_color'`,
),
borderObjectColor: (value: BorderObject) =>
invariant(
'color' in value,
'border',
JSON.stringify(value),
`should contain a 'color' property when provided as an object`,
),
background: (value: ImgOpt['background']) =>
invariant(
includes(value, backgroundOptions) || value.match(colorRegex),
'background',
value,
`${shouldBeOneOf(backgroundOptions)} or a color`,
),
overlay: () => {
// No validation
},
underlay: () => {
// No validation
},
textCaptionStyles: (value: StringOverlayStyle) => {
const {
fontFamily,
fontSize,
fontWeight,
fontStyle,
textDecoration,
textAlign,
stroke,
letterSpacing,
lineSpacing,
} = value
invariant(
fontFamily && fontSize && isNumber(fontSize),
'text caption',
JSON.stringify(value),
`required options are 'fontFamily' and 'fontSize'`,
'/image_transformations#adding_text_captions',
)
invariant(
(!fontWeight || includes(fontWeight, ['normal', 'bold'])) &&
(!fontStyle || includes(fontStyle, ['normal', 'italic'])) &&
(!textDecoration || includes(textDecoration, ['none', 'underline', 'strikethrough'])) &&
(!textAlign ||
includes(textAlign, ['left', 'center', 'right', 'start', 'end', 'justify'])) &&
(!stroke || includes(stroke, ['none', 'stroke'])) &&
(!letterSpacing || isNumber(letterSpacing)) &&
(!lineSpacing || isNumber(lineSpacing)),
'text caption',
JSON.stringify(value),
`options are invalid`,
'/image_transformations#adding_text_captions',
)
},
defaultImage: (value: ImgOpt['defaultImage']) =>
invariant(
value.match(/^[\w+-]+\.[\w]{3,4}$/) &&
includes(value.substr(value.indexOf('.') + 1), formatOptions),
'defaultImage',
value,
`must include a file extension which ${shouldBeOneOf(formatOptions)}`,
),
delay: (value: ImgOpt['delay']) =>
invariant(isNumber(value) && value >= 0, 'delay', value, `must be a positive number`),
color: (value: ImgOpt['color']) =>
invariant(
value.match(colorRegex),
'color',
value,
`must be a named color, short #rgb[a] or long #rrggbb[aa] hex value`,
),
colorSpace: (value: ImgOpt['colorSpace']) =>
invariant(
includes(value, colorSpaceOptions) || value.match(/^icc:[\w+-]+\.[\w]{3,4}$/),
'colorSpace',
value,
`${shouldBeOneOf(colorSpaceOptions)} or 'icc:(public_id)'`,
),
dpr: (value: ImgOpt['dpr']) =>
invariant(
value === 'auto' || (isNumber(value) && value > 0),
'dpr',
value,
'should be `auto` or a number greater than 0',
),
page: (value: ImgOpt['page']) =>
invariant(isNumber(value) && value > 0, 'page', value, 'should be an integer greater than 0'),
density: (value: ImgOpt['density']) =>
invariant(
isNumber(value) && 0 < value && value <= 300,
'density',
value,
'should be a number greater than 0 up to 300',
),
flags: (value: ImgOpt['flags']): asserts value is ImgOpt['flags'] => {
invariant(
(Array.isArray(value) ? value : value.split('.')).every((flag) =>
includes(flag, flagOptions),
),
'flags',
JSON.stringify(value),
`${shouldBeOneOf(flagOptions)}, an array of options or '.' separated options`,
)
},
}
const urlParameters: Record<keyof ImageTransform, string> = {
width: 'w_',
height: 'h_',
crop: 'c_',
aspectRatio: 'ar_',
gravity: 'g_',
zoom: 'z_',
x: 'x_',
y: 'y_',
fetchFormat: 'f_',
format: 'f_',
quality: 'q_',
radius: 'r_',
angle: 'a_',
effect: 'e_',
opacity: 'o_',
border: 'bo_',
background: 'b_',
overlay: 'l_',
underlay: 'u_',
defaultImage: 'd_',
delay: 'dl_',
color: 'co_',
colorSpace: 'cs_',
dpr: 'dpr_',
page: 'pg_',
density: 'dn_',
flags: 'fl_',
}
const compileTextCaption = (value: StringOverlayStyle): string => {
let publicIdStringStyle = value.publicId
if (!publicIdStringStyle) {
if (process.env.NODE_ENV !== 'production') {
validate.textCaptionStyles(value)
}
const { letterSpacing, lineSpacing } = value
publicIdStringStyle = [
value.fontFamily && encodeURIComponent(value.fontFamily),
value.fontSize,
value.fontWeight,
value.fontStyle,
value.textDecoration,
value.textAlign,
value.stroke,
letterSpacing ? `letter_spacing_${letterSpacing}` : 0,
lineSpacing ? `line_spacing_${lineSpacing}` : 0,
]
.filter((option) => option && option !== 'normal' && option !== 'none')
.join('_')
}
return `text:${publicIdStringStyle}:${encodeURIComponent(value.text)}`
}
const compileBorder = (value: BorderObject): string => {
if (process.env.NODE_ENV !== 'production') {
validate.borderObjectColor(value as BorderObject)
}
if (typeof value.width !== 'string' || value.width.substr(value.width.length - 2, 2) !== 'px') {
value.width = (value.width || 1) + 'px'
}
return value.width + '_solid_' + value.color
}
export function compileImageParameter<T extends keyof ImageTransform>(
parameter: T,
value: ImageTransform[T] | string,
) {
if (value == null) {
return false
}
switch (parameter) {
case 'flags':
value = Array.isArray(value) ? value.join('.') : value
break
case 'overlay':
case 'underlay':
if (typeof value === 'object') {
value = compileTextCaption(value as StringOverlayStyle)
}
break
case 'border':
if (typeof value === 'object') {
value = compileBorder(value as BorderObject)
}
value = value.toString().toLowerCase().replace('#', 'rgb:')
break
case 'color':
case 'background':
value = value.toString().replace('#', 'rgb:')
// no default
}
if (process.env.NODE_ENV !== 'production') {
if (!validate[parameter]) {
throw new Error(`Cloudinary Image :: unknown transform parameter provided: '${parameter}'`)
}
// @ts-ignore
validate[parameter](value)
}
return urlParameters[parameter] + value
}
const compileImageTransform = (transform: ImageTransform) =>
(Object.keys(transform) as (keyof ImageTransform)[])
.map((param) => compileImageParameter(param, transform[param]))
.filter(Boolean)
.join(',')
export const compileImageTransforms = (
transform: ImageTransform | ImageTransform[],
defaultTransform?: ImageTransform,
) => {
const compiledTransform = Array.isArray(transform)
? transform.map(compileImageTransform).join('/')
: compileImageTransform({ ...defaultTransform, ...transform })
return compiledTransform ? `/${compiledTransform}` : ''
}