This commit is contained in:
syuilo
2017-12-11 13:33:33 +09:00
parent 9852c57b8f
commit e36a708132
8 changed files with 157 additions and 11 deletions

View File

@ -110,7 +110,7 @@ const addFile = async (
}
}
const [wh, folder] = await Promise.all([
const [wh, averageColor, folder] = await Promise.all([
// Width and height (when image)
(async () => {
// 画像かどうか
@ -125,14 +125,45 @@ const addFile = async (
return null;
}
log('calculate image width and height...');
// Calculate width and height
const g = gm(fs.createReadStream(path), name);
const size = await prominence(g).size();
log('image width and height is calculated');
log(`image width and height is calculated: ${size.width}, ${size.height}`);
return [size.width, size.height];
})(),
// average color (when image)
(async () => {
// 画像かどうか
if (!/^image\/.*$/.test(mime)) {
return null;
}
const imageType = mime.split('/')[1];
// 画像でもPNGかJPEGでないならスキップ
if (imageType != 'png' && imageType != 'jpeg') {
return null;
}
log('calculate average color...');
const buffer = await prominence(gm(fs.createReadStream(path), name)
.setFormat('ppm')
.resize(1, 1)) // 1pxのサイズに縮小して平均色を取得するというハック
.toBuffer();
const r = buffer.readUInt8(buffer.length - 3);
const g = buffer.readUInt8(buffer.length - 2);
const b = buffer.readUInt8(buffer.length - 1);
log(`average color is calculated: ${r}, ${g}, ${b}`);
return [r, g, b];
})(),
// folder
(async () => {
if (!folderId) {
@ -188,6 +219,10 @@ const addFile = async (
properties['height'] = wh[1];
}
if (averageColor) {
properties['average_color'] = averageColor;
}
return addToGridFS(detectedName, readable, mime, {
user_id: user._id,
folder_id: folder !== null ? folder._id : null,

View File

@ -38,9 +38,15 @@ module.exports = async (file, params, user): Promise<any> => {
const [folderId = null, folderIdErr] = $(params.folder_id).optional.nullable.id().$;
if (folderIdErr) throw 'invalid folder_id param';
// Create file
const driveFile = await create(user, file.path, name, null, folderId);
try {
// Create file
const driveFile = await create(user, file.path, name, null, folderId);
// Serialize
return serialize(driveFile);
// Serialize
return serialize(driveFile);
} catch (e) {
console.error(e);
throw e;
}
};