Skip to content

Commit

Permalink
Decouple image resizing and optimization (strapi#14029)
Browse files Browse the repository at this point in the history
Co-authored-by: Alexandre Bodin <[email protected]>
  • Loading branch information
WalkingPizza and alexandrebodin authored Mar 22, 2023
1 parent 0895e36 commit edc2bdc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
14 changes: 14 additions & 0 deletions packages/core/upload/server/services/image-manipulation.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'];

Expand Down Expand Up @@ -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 {
Expand All @@ -224,6 +237,7 @@ module.exports = () => ({
isSupportedImage,
isFaultyImage,
isOptimizableImage,
isResizableImage,
isImage,
getDimensions,
generateResponsiveFormats,
Expand Down
5 changes: 3 additions & 2 deletions packages/core/upload/server/services/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand All @@ -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));
Expand Down

0 comments on commit edc2bdc

Please sign in to comment.