strapi/packages/core/upload/server/services/image-manipulation.js

219 lines
5.6 KiB
JavaScript
Raw Normal View History

'use strict';
/**
* Image manipulation functions
*/
2022-01-04 19:21:05 +01:00
const fs = require('fs');
const { join } = require('path');
const sharp = require('sharp');
2022-08-03 09:26:26 +02:00
const { ForbiddenError } = require('@strapi/utils/lib/errors');
2021-08-19 22:27:00 +02:00
const { getService } = require('../utils');
const { bytesToKbytes } = require('../utils/file');
2022-06-16 17:38:14 +01:00
const FORMATS_TO_PROCESS = ['jpeg', 'png', 'webp', 'tiff', 'svg', 'gif'];
const FORMATS_TO_OPTIMIZE = ['jpeg', 'png', 'webp', 'tiff'];
2022-02-08 15:24:32 +01:00
2022-01-04 19:21:05 +01:00
const writeStreamToFile = (stream, path) =>
new Promise((resolve, reject) => {
const writeStream = fs.createWriteStream(path);
2022-08-03 09:26:26 +02:00
// Reject promise if there is an error with the provided stream
stream.on('error', reject);
2022-01-04 19:21:05 +01:00
stream.pipe(writeStream);
writeStream.on('close', resolve);
writeStream.on('error', reject);
});
const getMetadata = file =>
new Promise((resolve, reject) => {
const pipeline = sharp();
pipeline
.metadata()
.then(resolve)
.catch(reject);
file.getStream().pipe(pipeline);
});
2022-01-04 19:21:05 +01:00
const getDimensions = async file => {
const { width = null, height = null } = await getMetadata(file);
return { width, height };
};
const THUMBNAIL_RESIZE_OPTIONS = {
width: 245,
height: 156,
fit: 'inside',
};
const resizeFileTo = async (file, options, { name, hash }) => {
const filePath = join(file.tmpWorkingDirectory, hash);
2022-01-04 19:21:05 +01:00
await writeStreamToFile(file.getStream().pipe(sharp().resize(options)), filePath);
2022-01-04 19:21:05 +01:00
const newFile = {
name,
hash,
ext: file.ext,
mime: file.mime,
path: file.path || null,
getStream: () => fs.createReadStream(filePath),
};
2022-01-04 19:21:05 +01:00
const { width, height, size } = await getMetadata(newFile);
2022-01-04 19:21:05 +01:00
Object.assign(newFile, { width, height, size: bytesToKbytes(size) });
return newFile;
};
const generateThumbnail = async file => {
2022-01-04 19:21:05 +01:00
if (
file.width > THUMBNAIL_RESIZE_OPTIONS.width ||
file.height > THUMBNAIL_RESIZE_OPTIONS.height
) {
const newFile = await resizeFileTo(file, THUMBNAIL_RESIZE_OPTIONS, {
name: `thumbnail_${file.name}`,
hash: `thumbnail_${file.hash}`,
});
2022-01-04 19:21:05 +01:00
return newFile;
}
return null;
};
2022-08-03 09:26:26 +02:00
/**
* Optimize image by:
* - auto orienting image based on EXIF data
* - reduce image quality
*
*/
const optimize = async file => {
2021-08-19 22:27:00 +02:00
const { sizeOptimization = false, autoOrientation = false } = await getService(
'upload'
).getSettings();
2022-01-04 19:21:05 +01:00
const newFile = { ...file };
2022-08-03 09:26:26 +02:00
try {
const { width, height, size, format } = await getMetadata(newFile);
2022-08-03 09:26:26 +02:00
if (sizeOptimization || autoOrientation) {
const transformer = sharp();
// reduce image quality
transformer[format]({ quality: sizeOptimization ? 80 : 100 });
// rotate image based on EXIF data
if (autoOrientation) {
transformer.rotate();
}
const filePath = join(file.tmpWorkingDirectory, `optimized-${file.hash}`);
await writeStreamToFile(file.getStream().pipe(transformer), filePath);
newFile.getStream = () => fs.createReadStream(filePath);
2022-02-08 15:24:32 +01:00
}
2022-01-04 19:21:05 +01:00
2022-08-03 09:26:26 +02:00
const { width: newWidth, height: newHeight, size: newSize } = await getMetadata(newFile);
2022-01-04 19:21:05 +01:00
2022-08-03 09:26:26 +02:00
if (newSize > size) {
// Ignore optimization if output is bigger than original
return Object.assign({}, file, { width, height, size: bytesToKbytes(size) });
}
2022-01-04 19:21:05 +01:00
2022-08-03 09:26:26 +02:00
return Object.assign(newFile, {
width: newWidth,
height: newHeight,
size: bytesToKbytes(newSize),
});
} catch {
throw new ForbiddenError('File is not a supported image');
2022-02-08 15:24:32 +01:00
}
};
const DEFAULT_BREAKPOINTS = {
large: 1000,
medium: 750,
small: 500,
};
2021-08-06 18:09:49 +02:00
const getBreakpoints = () => strapi.config.get('plugin.upload.breakpoints', DEFAULT_BREAKPOINTS);
2022-08-03 09:26:26 +02:00
//
const generateResponsiveFormats = async file => {
2021-08-19 22:27:00 +02:00
const { responsiveDimensions = false } = await getService('upload').getSettings();
if (!responsiveDimensions) return [];
2022-01-04 19:21:05 +01:00
const originalDimensions = await getDimensions(file);
const breakpoints = getBreakpoints();
return Promise.all(
Object.keys(breakpoints).map(key => {
const breakpoint = breakpoints[key];
if (breakpointSmallerThan(breakpoint, originalDimensions)) {
return generateBreakpoint(key, { file, breakpoint, originalDimensions });
}
})
);
};
const generateBreakpoint = async (key, { file, breakpoint }) => {
2022-01-04 19:21:05 +01:00
const newFile = await resizeFileTo(
file,
{
width: breakpoint,
height: breakpoint,
fit: 'inside',
},
{
name: `${key}_${file.name}`,
hash: `${key}_${file.hash}`,
}
2022-01-04 19:21:05 +01:00
);
return {
key,
file: newFile,
};
};
const breakpointSmallerThan = (breakpoint, { width, height }) => {
return breakpoint < width || breakpoint < height;
};
2022-06-16 19:49:30 +01:00
// TODO V5: remove isSupportedImage
const isSupportedImage = (...args) => {
process.emitWarning(
'[deprecated] In future versions, `isSupportedImage` will be removed. Replace it with `isImage` or `isOptimizableImage` instead.'
);
return isOptimizableImage(...args);
};
2022-06-16 17:38:14 +01:00
const isOptimizableImage = async file => {
let format;
try {
const metadata = await getMetadata(file);
format = metadata.format;
} catch (e) {
// throw when the file is not a supported image
return false;
}
return format && FORMATS_TO_OPTIMIZE.includes(format);
};
const isImage = async file => {
2022-02-08 15:24:32 +01:00
let format;
try {
const metadata = await getMetadata(file);
format = metadata.format;
} catch (e) {
// throw when the file is not a supported image
return false;
}
return format && FORMATS_TO_PROCESS.includes(format);
};
2021-07-08 11:20:13 +02:00
module.exports = () => ({
2022-06-16 19:49:30 +01:00
isSupportedImage,
2022-06-16 17:38:14 +01:00
isOptimizableImage,
isImage,
getDimensions,
generateResponsiveFormats,
generateThumbnail,
optimize,
2021-07-08 11:20:13 +02:00
});