Skip to content

Instantly share code, notes, and snippets.

@abinavseelan
Created August 24, 2017 13:35
Show Gist options
  • Save abinavseelan/877c52b659796f3171ee946e2397cc69 to your computer and use it in GitHub Desktop.
Save abinavseelan/877c52b659796f3171ee946e2397cc69 to your computer and use it in GitHub Desktop.
Medium - Image Manipulation using NodeJS - Resize endpoint
const express = require('express');
const app = express();
const gm = require('gm');
const fs = require('fs');
const port = 1337;
app.get('/ping', (request, response) => {
response.send('Pong!');
});
app.get('/resize/:width/:height', (request, response) => {
const { width, height } = request.params;
// Simple checks to see if the value was passed in the url
// If it wasn't, the value is changed from undefined to null
width = width || null;
height = height || null;
gm('/path/to/image/file')
.resize(width, height)
.write('./tmp.png', (err) => {
if (err) {
console.log(err);
} else {
response.sendFile('./tmp.png');
}
})
fs.unlinkSync('./tmp.png');
});
app.get('/crop/:width/:height', (request, response) => {
const { width, height } = request.params;
gm('/path/to/image/file')
.gravity('Center')
.crop(width, height)
.write('./tmp.png', (err) => {
if (err) {
console.log(err);
} else {
response.sendFile('./tmp.png');
}
})
fs.unlinkSync('./tmp.png');
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment