2020-03-05 17:48:07 +01:00
|
|
|
'use strict';
|
|
|
|
/**
|
|
|
|
* Image manipulation functions
|
|
|
|
*/
|
|
|
|
const sharp = require('sharp');
|
|
|
|
|
2020-03-06 18:41:48 +01:00
|
|
|
const { bytesToKbytes } = require('../utils/file');
|
2020-03-06 17:00:25 +01:00
|
|
|
|
|
|
|
const getMetadatas = buffer =>
|
2020-03-05 17:48:07 +01:00
|
|
|
sharp(buffer)
|
|
|
|
.metadata()
|
2020-03-06 17:00:25 +01:00
|
|
|
.catch(() => ({})); // ingore errors
|
|
|
|
|
|
|
|
const getDimensions = buffer =>
|
|
|
|
getMetadatas(buffer)
|
2020-03-05 17:48:07 +01:00
|
|
|
.then(({ width, height }) => ({ width, height }))
|
2020-03-06 17:00:25 +01:00
|
|
|
.catch(() => ({})); // ingore errors
|
2020-03-05 17:48:07 +01:00
|
|
|
|
2020-03-06 17:00:25 +01:00
|
|
|
const THUMBNAIL_RESIZE_OPTIONS = {
|
2020-03-05 17:48:07 +01:00
|
|
|
width: 245,
|
|
|
|
height: 156,
|
|
|
|
fit: 'inside',
|
|
|
|
};
|
|
|
|
|
2020-03-06 17:00:25 +01:00
|
|
|
const resizeTo = (buffer, options) =>
|
|
|
|
sharp(buffer)
|
|
|
|
.resize(options)
|
2020-03-05 17:48:07 +01:00
|
|
|
.toBuffer()
|
2020-03-06 17:00:25 +01:00
|
|
|
.catch(() => null);
|
|
|
|
|
|
|
|
const generateThumbnail = async file => {
|
|
|
|
const { width, height } = await getDimensions(file.buffer);
|
|
|
|
|
|
|
|
if (width > THUMBNAIL_RESIZE_OPTIONS.width || height > THUMBNAIL_RESIZE_OPTIONS.height) {
|
|
|
|
const newBuff = await resizeTo(file.buffer, THUMBNAIL_RESIZE_OPTIONS);
|
|
|
|
|
|
|
|
if (newBuff) {
|
|
|
|
const { width, height, size } = await getMetadatas(newBuff);
|
|
|
|
|
|
|
|
return {
|
2020-03-09 09:02:51 +01:00
|
|
|
hash: `thumbnail_${file.hash}`,
|
2020-03-05 17:48:07 +01:00
|
|
|
ext: file.ext,
|
2020-03-06 17:00:25 +01:00
|
|
|
mime: file.mime,
|
|
|
|
width,
|
|
|
|
height,
|
|
|
|
size: bytesToKbytes(size),
|
|
|
|
buffer: newBuff,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
2020-03-05 17:48:07 +01:00
|
|
|
};
|
|
|
|
|
2020-03-08 12:59:21 +01:00
|
|
|
const optimize = async buffer => {
|
2020-03-08 18:43:50 +01:00
|
|
|
const { sizeOptimization = false } = await strapi.plugins.upload.services.upload.getSettings();
|
|
|
|
|
|
|
|
if (!sizeOptimization) return { buffer };
|
|
|
|
|
|
|
|
return sharp(buffer)
|
|
|
|
.toBuffer({ resolveWithObject: true })
|
|
|
|
.then(({ data, info }) => ({
|
|
|
|
buffer: data,
|
|
|
|
info: {
|
|
|
|
width: info.width,
|
|
|
|
height: info.height,
|
|
|
|
size: bytesToKbytes(info.size),
|
|
|
|
},
|
|
|
|
}))
|
|
|
|
.catch(() => ({ buffer }));
|
2020-03-08 12:59:21 +01:00
|
|
|
};
|
|
|
|
|
2020-03-05 17:48:07 +01:00
|
|
|
module.exports = {
|
|
|
|
getDimensions,
|
|
|
|
generateThumbnail,
|
2020-03-06 17:00:25 +01:00
|
|
|
bytesToKbytes,
|
2020-03-08 12:59:21 +01:00
|
|
|
optimize,
|
2020-03-05 17:48:07 +01:00
|
|
|
};
|