Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Last active May 1, 2016 16:30
Show Gist options
  • Save joshwcomeau/35949a6db9d53179b3ab394b8320bf9a to your computer and use it in GitHub Desktop.
Save joshwcomeau/35949a6db9d53179b3ab394b8320bf9a to your computer and use it in GitHub Desktop.
convert-to-async
app.post('/process-upload', upload.single('image'), (req, res) => {
// Start by reading the uploaded file
fs.readFile(req.file.path, (err, originalFileBuffer) => {
if (err) throw err;
// Resize the image to 32x16, and convert to .png for consistency
imageMagick.convert({
srcData: originalFileBuffer,
width: 32,
height: 16,
format: 'PNG'
}, (err, smallFileBuffer) => {
if (err) throw err;
// Call to a utility function to get the new write-path.
// Not important in this context, so I've excluded it.
const newFilename = getPathForNewFile(req.file);
// Work out the RGBA values for every pixel in the image.
const pixels = imageMagick.getConstPixels({
srcData: smallFileBuffer,
x: 0,
y: 0,
columns: 32,
rows: 16
});
// Save the resized .png to disk, for reference.
fs.writeFile(newFilename, smallFileBuffer, (err, data) => {
if (err) throw err;
// We're done! Send the pixels to the client.
return res.json({ done: true, pixels });
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment