Refactor uploads
This commit is contained in:
parent
75a46212da
commit
f59b9a5d22
14 changed files with 297 additions and 269 deletions
|
@ -1,33 +1,71 @@
|
|||
import fs from 'mz/fs';
|
||||
import lwip from 'lwip';
|
||||
import debugname from 'debug';
|
||||
const debug = debugname('hostr-api:resize');
|
||||
import lwip from 'lwip';
|
||||
import imageType from 'image-type';
|
||||
|
||||
const supported = ['jpg', 'png', 'gif'];
|
||||
|
||||
export default function(input, size) {
|
||||
debug('Resizing');
|
||||
|
||||
const type = imageType(input);
|
||||
|
||||
if (!type.ext || supported.indexOf(type.ext) < 0) {
|
||||
throw new Error('Not a supported image.');
|
||||
}
|
||||
|
||||
function cover(path, type, size) {
|
||||
return new Promise((resolve, reject) => {
|
||||
lwip.open(input, type.ext, (errIn, image) => {
|
||||
lwip.open(path, type, (errIn, image) => {
|
||||
debug('Image Opened');
|
||||
if (errIn) {
|
||||
return reject(errIn);
|
||||
reject(errIn);
|
||||
}
|
||||
|
||||
image.cover(size.width, size.height, (errOut, resized) => {
|
||||
debug('Image Resized');
|
||||
if (errOut) {
|
||||
return reject(errOut);
|
||||
reject(errOut);
|
||||
}
|
||||
|
||||
resized.toBuffer(type.ext, (errBuf, buffer) => {
|
||||
resized.toBuffer(type, (errBuf, buffer) => {
|
||||
debug('Image Buffered');
|
||||
if (errBuf) {
|
||||
reject(errBuf);
|
||||
}
|
||||
resolve(buffer);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function scale(path, type, size) {
|
||||
return new Promise((resolve, reject) => {
|
||||
lwip.open(path, type, (errIn, image) => {
|
||||
debug('Image Opened');
|
||||
if (errIn) {
|
||||
reject(errIn);
|
||||
}
|
||||
|
||||
image.cover(size.width, size.height, (errOut, resized) => {
|
||||
debug('Image Resized');
|
||||
if (errOut) {
|
||||
reject(errOut);
|
||||
}
|
||||
|
||||
resized.toBuffer(type, (errBuf, buffer) => {
|
||||
debug('Image Buffered');
|
||||
if (errBuf) {
|
||||
reject(errBuf);
|
||||
}
|
||||
resolve(buffer);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export default function resize(path, type, currentSize, newSize) {
|
||||
debug('Resizing');
|
||||
const ratio = 970 / currentSize.width;
|
||||
if (newSize.width <= 150) {
|
||||
debug('Cover');
|
||||
return cover(path, type, newSize);
|
||||
} else if (newSize.width > 970 && ratio > 1) {
|
||||
debug('Scale');
|
||||
newSize.height = currentSize.height * ratio;
|
||||
return scale(path, type, newSize);
|
||||
}
|
||||
debug('Copy');
|
||||
return fs.readFile(path);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue