2016-05-25 21:03:07 +01:00
|
|
|
import fs from 'mz/fs';
|
2018-06-02 15:50:39 +00:00
|
|
|
import jimp from 'jimp';
|
2015-07-09 23:01:43 +01:00
|
|
|
import debugname from 'debug';
|
2018-06-02 18:07:00 +00:00
|
|
|
|
2015-07-09 23:01:43 +01:00
|
|
|
const debug = debugname('hostr-api:resize');
|
|
|
|
|
2018-06-02 15:50:39 +00:00
|
|
|
const types = {
|
|
|
|
jpg: jimp.MIME_JPEG,
|
|
|
|
png: jimp.MIME_PNG,
|
|
|
|
gif: jimp.MIME_JPEG,
|
2018-06-02 18:07:00 +00:00
|
|
|
};
|
2018-06-02 15:50:39 +00:00
|
|
|
|
2018-08-11 12:53:42 +01:00
|
|
|
const align = jimp.HORIZONTAL_ALIGN_CENTER | jimp.VERTICAL_ALIGN_MIDDLE;
|
2015-07-09 23:01:43 +01:00
|
|
|
|
2018-08-11 12:53:42 +01:00
|
|
|
async function cover(path, type, size) {
|
|
|
|
const image = await jimp.read(path);
|
|
|
|
debug('Image Opened');
|
|
|
|
debug(size);
|
|
|
|
const resized = await image.cover(size.width, size.height, align);
|
|
|
|
debug('Image Resized');
|
2016-05-24 21:33:09 +01:00
|
|
|
|
2018-08-11 12:53:42 +01:00
|
|
|
return await resized.quality(80).getBufferAsync(types[type]);
|
2016-05-25 21:03:07 +01:00
|
|
|
}
|
2016-05-24 21:33:09 +01:00
|
|
|
|
2018-08-11 12:53:42 +01:00
|
|
|
async function scale(path, type, size) {
|
|
|
|
const image = await jimp.read(path);
|
|
|
|
debug('Image Opened');
|
2016-05-25 21:03:07 +01:00
|
|
|
|
2018-08-11 12:53:42 +01:00
|
|
|
const resized = await image.cover(size.width, size.height, align);
|
|
|
|
debug('Image Resized');
|
2016-05-24 21:33:09 +01:00
|
|
|
|
2018-08-11 12:53:42 +01:00
|
|
|
return await resized.quality(80).getBufferAsync(types[type]);
|
2015-07-09 23:01:43 +01:00
|
|
|
}
|
2016-05-25 21:03:07 +01:00
|
|
|
|
|
|
|
export default function resize(path, type, currentSize, newSize) {
|
|
|
|
debug('Resizing');
|
|
|
|
const ratio = 970 / currentSize.width;
|
2016-06-06 17:34:04 +01:00
|
|
|
debug(newSize.width, ratio);
|
2016-05-25 21:03:07 +01:00
|
|
|
if (newSize.width <= 150) {
|
|
|
|
debug('Cover');
|
|
|
|
return cover(path, type, newSize);
|
2016-06-06 17:34:04 +01:00
|
|
|
} else if (newSize.width >= 970 && ratio < 1) {
|
2016-05-25 21:03:07 +01:00
|
|
|
debug('Scale');
|
2016-06-06 15:37:00 +01:00
|
|
|
newSize.height = currentSize.height * ratio; // eslint-disable-line no-param-reassign
|
2016-05-25 21:03:07 +01:00
|
|
|
return scale(path, type, newSize);
|
|
|
|
}
|
|
|
|
debug('Copy');
|
|
|
|
return fs.readFile(path);
|
|
|
|
}
|