You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
101 lines
2.7 KiB
101 lines
2.7 KiB
/* eslint-disable no-param-reassign */
|
|
import sharp from 'sharp';
|
|
|
|
/** image size supported */
|
|
const Sizes = [50, 100, 200, 300, 400, 500, 600, 700, 800];
|
|
|
|
function transformer(options, transformOptions) {
|
|
let imageStream = sharp();
|
|
|
|
if (transformOptions.resize) {
|
|
const keys = Object.keys(options);
|
|
for (let index = 0; index < keys.length; index += 1) {
|
|
const value = options[keys[index]];
|
|
if (value) {
|
|
imageStream = resolveImageStream(
|
|
keys[index],
|
|
value,
|
|
transformOptions.resize,
|
|
imageStream
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
return imageStream;
|
|
}
|
|
|
|
const objectHasOwnProperty = (source, prop) =>
|
|
Object.prototype.hasOwnProperty.call(source, prop);
|
|
|
|
const hasProp = (value) =>
|
|
typeof value === 'object' && objectHasOwnProperty(value, 'type');
|
|
|
|
const validateFormat = (value) => {
|
|
if (hasProp(value)) {
|
|
return value.type;
|
|
}
|
|
return value;
|
|
};
|
|
|
|
const validateValue = (value) => {
|
|
if (typeof value === 'boolean') {
|
|
return null;
|
|
}
|
|
return value;
|
|
};
|
|
|
|
const resolveImageStream = (key, value, size, imageStream) => {
|
|
if (key === 'resize') {
|
|
imageStream = imageStream.resize(
|
|
size.width,
|
|
size.height,
|
|
Object.assign(value, size.options)
|
|
);
|
|
} else if (key === 'crop') {
|
|
imageStream = imageStream[key](value);
|
|
} else if (key === 'toFormat') {
|
|
imageStream = imageStream.toFormat(
|
|
validateFormat(value),
|
|
value.options
|
|
);
|
|
} else {
|
|
const valid = validateValue(value);
|
|
imageStream = imageStream[key](valid);
|
|
}
|
|
return imageStream;
|
|
};
|
|
|
|
const getSharpOptions = (options) => ({
|
|
resize: options.resize,
|
|
background: options.background,
|
|
crop: options.crop,
|
|
embed: options.embed,
|
|
max: options.max,
|
|
min: options.min,
|
|
toFormat: options.toFormat,
|
|
extract: options.extract,
|
|
trim: options.trim,
|
|
flatten: options.flatten,
|
|
extend: options.extend,
|
|
negate: options.negate,
|
|
rotate: options.rotate,
|
|
flip: options.flip,
|
|
flop: options.flop,
|
|
blur: options.blur,
|
|
sharpen: options.sharpen,
|
|
gamma: options.gamma,
|
|
grayscale: options.grayscale,
|
|
greyscale: options.greyscale,
|
|
normalize: options.normalize,
|
|
normalise: options.normalise,
|
|
convolve: options.convolve,
|
|
threshold: options.threshold,
|
|
toColourspace: options.toColourspace,
|
|
toColorspace: options.toColorspace,
|
|
ignoreAspectRatio: options.ignoreAspectRatio,
|
|
withMetadata: options.withMetadata,
|
|
withoutEnlargement: options.withoutEnlargement
|
|
});
|
|
|
|
module.exports = { Sizes, transformer, getSharpOptions };
|
|
|