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

195 lines
4.8 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');
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);
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;
};
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-02-08 15:24:32 +01:00
const { width, height, size, format } = await getMetadata(newFile);
2022-02-08 15:24:32 +01:00
if (sizeOptimization || autoOrientation) {
const transformer = sharp();
transformer[format]({ quality: sizeOptimization ? 80 : 100 });
if (autoOrientation) {
transformer.rotate();
}
2022-01-04 19:21:05 +01:00
const filePath = join(file.tmpWorkingDirectory, `optimized-${file.hash}`);
2022-02-08 15:24:32 +01:00
await writeStreamToFile(file.getStream().pipe(transformer), filePath);
2022-01-04 19:21:05 +01:00
newFile.getStream = () => fs.createReadStream(filePath);
}
2022-02-08 15:24:32 +01:00
const { width: newWidth, height: newHeight, size: newSize } = await getMetadata(newFile);
2022-01-04 19:21:05 +01:00
2022-02-08 15:24:32 +01:00
if (newSize > size) {
// Ignore optimization if output is bigger than original
return Object.assign({}, file, { width, height, size: bytesToKbytes(size) });
}
return Object.assign(newFile, {
width: newWidth,
height: newHeight,
size: bytesToKbytes(newSize),
});
};
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);
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 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 17:38:14 +01:00
isOptimizableImage,
isImage,
getDimensions,
generateResponsiveFormats,
generateThumbnail,
optimize,
2021-07-08 11:20:13 +02:00
});