Skip to content

Instantly share code, notes, and snippets.

@Ratismal
Created March 14, 2017 05:14
Show Gist options
  • Save Ratismal/67f62ba924d66a2d359874bbc49fcf55 to your computer and use it in GitHub Desktop.
Save Ratismal/67f62ba924d66a2d359874bbc49fcf55 to your computer and use it in GitHub Desktop.
/**
* This module provides a function `distortImage` that takes a URL of an image and distorts it.
* Returns a promise containing a buffer.
*
* For dependencies, you need
* 1. The ImageMagick binary (https://www.imagemagick.org/script/download.php)
* 2. The GraphicsMagick JS library (https://github.com/aheckmann/gm)
* - `npm i gm`
* 3. The Jimp library (https://github.com/oliver-moran/jimp)
* - `npm i jimp`
**/
const im = require('gm').subClass({
imageMagick: true
});
const Jimp = require('jimp');
function distortImage(url) {
return new Promise((resolve, reject) => {
Jimp.read(url).then(img1 => { // Use Jimp to read from a url
if (img1.bitmap.width == 400 && img1.bitmap.height == 620) // Verify the correct dimensions before cropping
img1.crop(27, 69, 344, 410); // Crop the card contents
const filters = [
{ apply: getRandomInt(0, 1) == 1 ? 'desaturate' : 'saturate', params: [getRandomInt(40, 80)] },
{ apply: 'spin', params: [getRandomInt(10, 350)] }
];
img1.color(filters); // Do some recolouring
img1.getBuffer(Jimp.MIME_PNG, (err, buffer) => {
if (err) {
reject(err); return;
}
let img2 = im(buffer); // Read into ImageMagick for manipulation
let horizRoll = getRandomInt(0, img1.bitmap.width),
vertiRoll = getRandomInt(0, img1.bitmap.height);
img2.out('-implode').out(`-${getRandomInt(3, 10)}`);
img2.out('-roll').out(`+${horizRoll}+${vertiRoll}`);
img2.out('-swirl').out(`${getRandomInt(0, 1) == 1 ? '+' : '-'}${getRandomInt(120, 180)}`);
img2.setFormat('png').toBuffer(function (err, buffer) { // Export as buffer. We're done.
if (err) {
reject(err); return;
}
resolve(buffer);
});
});
});
});
}
function getRandomInt(min, max) { // generic random number generator
return Math.floor(Math.random() * (max - min + 1)) + min;
};
module.exports = distortImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment