resizing and optimizing jpeg images with mozjpeg

This commit is contained in:
azivner 2018-01-06 12:38:25 -05:00
parent 23a5e38e02
commit d9f29cbf27
5 changed files with 2170 additions and 87 deletions

2197
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -33,7 +33,11 @@
"fs-extra": "^4.0.2",
"helmet": "^3.9.0",
"html": "^1.0.0",
"imagemin": "^5.3.1",
"imagemin-mozjpeg": "^7.0.0",
"ini": "^1.3.4",
"jimp": "^0.2.28",
"multer": "^1.3.0",
"rand-token": "^0.4.0",
"request": "^2.83.0",
"request-promise": "^4.2.2",

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -6,6 +6,9 @@ const sql = require('../../services/sql');
const auth = require('../../services/auth');
const utils = require('../../services/utils');
const multer = require('multer')();
const imagemin = require('imagemin');
const imageminMozJpeg = require('imagemin-mozjpeg');
const jimp = require('jimp');
router.get('/:imageId/:filename', auth.checkApiAuth, async (req, res, next) => {
const image = await sql.getFirst("SELECT * FROM images WHERE image_id = ?", [req.params.imageId]);
@ -21,7 +24,6 @@ router.get('/:imageId/:filename', auth.checkApiAuth, async (req, res, next) => {
router.post('/upload', auth.checkApiAuth, multer.single('upload'), async (req, res, next) => {
const file = req.file;
console.log("File: ", file);
const imageId = utils.newNoteId();
@ -31,12 +33,15 @@ router.post('/upload', auth.checkApiAuth, multer.single('upload'), async (req, r
const now = utils.nowDate();
const resizedImage = await resize(file.buffer);
const optimizedImage = await optimize(resizedImage);
await sql.insert("images", {
image_id: imageId,
format: file.mimetype.substr(6),
name: file.originalname,
checksum: utils.hash(file.buffer),
data: file.buffer,
checksum: utils.hash(optimizedImage),
data: optimizedImage,
is_deleted: 0,
date_modified: now,
date_created: now
@ -48,4 +53,43 @@ router.post('/upload', auth.checkApiAuth, multer.single('upload'), async (req, r
});
});
const MAX_SIZE = 1000;
async function resize(buffer) {
const image = await jimp.read(buffer);
if (image.bitmap.width > image.bitmap.height && image.bitmap.width > MAX_SIZE) {
image.resize(MAX_SIZE, jimp.AUTO);
}
else if (image.bitmap.height > MAX_SIZE) {
image.resize(jimp.AUTO, MAX_SIZE);
}
else {
return buffer;
}
// we do resizing with max quality which will be trimmed during optimization step next
image.quality(100);
// getBuffer doesn't support promises so this workaround
return await new Promise((resolve, reject) => image.getBuffer(jimp.MIME_JPEG, (err, data) => {
if (err) {
reject(err);
}
else {
resolve(data);
}
}));
}
async function optimize(buffer) {
return await imagemin.buffer(buffer, {
plugins: [
imageminMozJpeg({
quality: 50
})
]
});
}
module.exports = router;