Decouple image resizing and optimization (#14029)

Co-authored-by: Alexandre Bodin <bodin.alex@gmail.com>
This commit is contained in:
Kevin Antonio Rateni Iatauro 2023-03-22 21:00:21 +11:00 committed by GitHub
parent 0895e36738
commit edc2bdcecd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 2 deletions

View File

@ -12,6 +12,7 @@ const {
} = require('@strapi/utils');
const { getService } = require('../utils');
const FORMATS_TO_RESIZE = ['jpeg', 'png', 'webp', 'tiff', 'gif'];
const FORMATS_TO_PROCESS = ['jpeg', 'png', 'webp', 'tiff', 'svg', 'gif', 'avif'];
const FORMATS_TO_OPTIMIZE = ['jpeg', 'png', 'webp', 'tiff', 'avif'];
@ -208,6 +209,18 @@ const isOptimizableImage = async (file) => {
return format && FORMATS_TO_OPTIMIZE.includes(format);
};
const isResizableImage = 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_RESIZE.includes(format);
};
const isImage = async (file) => {
let format;
try {
@ -224,6 +237,7 @@ module.exports = () => ({
isSupportedImage,
isFaultyImage,
isOptimizableImage,
isResizableImage,
isImage,
getDimensions,
generateResponsiveFormats,

View File

@ -187,7 +187,7 @@ module.exports = ({ strapi }) => ({
* @param {*} fileData
*/
async uploadImage(fileData) {
const { getDimensions, generateThumbnail, generateResponsiveFormats, isOptimizableImage } =
const { getDimensions, generateThumbnail, generateResponsiveFormats, isResizableImage } =
getService('image-manipulation');
// Store width and height of the original image
@ -206,6 +206,7 @@ module.exports = ({ strapi }) => ({
_.set(fileData, 'formats.thumbnail', thumbnailFile);
};
// Generate thumbnail and responsive formats
const uploadResponsiveFormat = async (format) => {
const { key, file } = format;
await getService('provider').upload(file);
@ -218,7 +219,7 @@ module.exports = ({ strapi }) => ({
uploadPromises.push(getService('provider').upload(fileData));
// Generate & Upload thumbnail and responsive formats
if (await isOptimizableImage(fileData)) {
if (await isResizableImage(fileData)) {
const thumbnailFile = await generateThumbnail(fileData);
if (thumbnailFile) {
uploadPromises.push(uploadThumbnail(thumbnailFile));