Skip to content

Commit

Permalink
feat: allows upload resizing to maintain aspect ratio
Browse files Browse the repository at this point in the history
  • Loading branch information
jmikrut committed Aug 6, 2021
1 parent 907f8fd commit dea54a4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
6 changes: 6 additions & 0 deletions demo/collections/Media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ const Media: PayloadCollectionConfig = {
staticDir: './media',
adminThumbnail: ({ doc }) => `/media/${doc.filename}`,
imageSizes: [
{
name: 'maintainedAspectRatio',
width: 1024,
height: null,
crop: 'center',
},
{
name: 'tablet',
width: 640,
Expand Down
4 changes: 2 additions & 2 deletions src/collections/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ const collectionSchema = joi.object().keys({
imageSizes: joi.array().items(
joi.object().keys({
name: joi.string(),
width: joi.number(),
height: joi.number(),
width: joi.number().allow(null),
height: joi.number().allow(null),
crop: joi.string(), // TODO: add further specificity with joi.xor
}),
),
Expand Down
23 changes: 15 additions & 8 deletions src/uploads/imageResizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,32 @@ export default async function resizeAndSave(
const sizes = imageSizes
.filter((desiredSize) => desiredSize.width < dimensions.width)
.map(async (desiredSize) => {
const resized = await sharp(sourceImage)
.resize(desiredSize.width, desiredSize.height, {
position: desiredSize.crop || 'centre',
});

const bufferObject = await resized.toBuffer({
resolveWithObject: true,
});

const outputImage = getOutputImage(savedFilename, desiredSize);
const imageNameWithDimensions = `${outputImage.name}-${outputImage.width}x${outputImage.height}.${outputImage.extension}`;
const imageNameWithDimensions = `${outputImage.name}-${bufferObject.info.width}x${bufferObject.info.height}.${outputImage.extension}`;
const imagePath = `${staticPath}/${imageNameWithDimensions}`;
const fileAlreadyExists = await fileExists(imagePath);

if (fileAlreadyExists) {
fs.unlinkSync(imagePath);
}

const output = await sharp(sourceImage)
.resize(desiredSize.width, desiredSize.height, {
position: desiredSize.crop || 'centre',
})
.toFile(imagePath);
await resized.toFile(imagePath);

return {
...desiredSize,
name: desiredSize.name,
width: bufferObject.info.width,
height: bufferObject.info.height,
filename: imageNameWithDimensions,
filesize: output.size,
filesize: bufferObject.info.size,
mimeType,
};
});
Expand Down

0 comments on commit dea54a4

Please sign in to comment.