Skip to content

Instantly share code, notes, and snippets.

@juanchehin
Created July 5, 2023 14:55
Show Gist options
  • Save juanchehin/c22e6417d13b0454890e6db6465854e1 to your computer and use it in GitHub Desktop.
Save juanchehin/c22e6417d13b0454890e6db6465854e1 to your computer and use it in GitHub Desktop.
const imagemin = require('imagemin');
const imageminJpegtran = require('imagemin-jpegtran');
const fs = require('fs');
/*
* Attempts to upload an image provided by a user to the server.
*
* Makes use of imagemin for image compression to reduce impact on server
* drive space.
*/
app.post('/uploadImage', function(req, res) {
if (!session.isAuthenticated) { return res.sendStatus(401); }
/*
* Write the raw image to disk.
*/
fs.writeFileSync(`/images/raw/${req.body.name}.png`, req.body.image);
/*
* Compresses a raw image, resulting in an optimized image with lower disk
* space required.
*/
const compressImage = async function() {
const res = await imagemin([`/images/raw/${req.body.name}.png`],
`/images/compressed/${req.body.name}.jpg`);
return res;
};
/*
* Compress the image provided by the requester, continue script
* expecution when compression is complete.
*/
const res = await compressImage();
/*
* Return a link to the compressed image to the client.
*/
return res.status(200)
.json({url: `https://media.mega-bank.com/images/${req.body.name}.jpg` });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment