Skip to content

Instantly share code, notes, and snippets.

@juliovedovatto
Created November 9, 2016 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliovedovatto/66751ba407e494fac4ca5c5a94ed7c36 to your computer and use it in GitHub Desktop.
Save juliovedovatto/66751ba407e494fac4ca5c5a94ed7c36 to your computer and use it in GitHub Desktop.
node gm - keep Aspect Ratio on resize and fill with blur background (with imagemagick)
var GM = require('gm').subClass({ imageMagick: true }),
Q = require('q'), // promisses support
fs = require('fs'),
path = require('path');
function create_thumb(img, dest_img, width, height) {
var deferred = Q.defer();
Q.when(get_image_size(img)).then(function (size) {
var thumb_width = width,
thumb_height = height,
blurred_img_width = 0,
blurred_img_height = 0,
tmp_file;
if (size.height > size.width) {
thumb_width = null;
thumb_height = height;
} else {
thumb_width = width;
thumb_height = null;
}
blurred_img_width = width;
blurred_img_height = Math.round(width * (size.height / size.width));
if (blurred_img_height < height) {
blurred_img_height = height;
blurred_img_width = Math.round(thumb_height * (size.width / size.height));
}
tmp_file = img.replace(new RegExp('(' + path.extname(img) + ')$', 'i'), '_$1'); // temporary file. Eg: file.jpg => file_.jpg
GM(img)
.resize(thumb_width, thumb_height)
.quality(90)
.strip()
.interlace('plane')
.write(tmp_file, function (err) {
if (err)
return deferred.reject(err);
GM(file).gravity('Center')
.resize(blurred_img_width, blurred_img_height, '!')
.crop(dimensions.w, dimensions.h)
.blur('0xsigma')
.quality(90)
.strip()
.interlace('plane')
.stream('jpeg', function (err, stream_img_blur) {
if (err)
return deferred.reject(err);
GM(stream_img_blur).compose('over')
.gravity('Center')
.composite(tmp_file)
.quality(90)
.strip()
.interlace('plane')
.write(dest_img, function (err) {
if (err)
deferred.reject(err);
try {
fs.unlinkSync(tmp_file);
} catch (err) {
return deferred.reject(err);
}
deferred.resolve(dest_img);
});
});
});
}, function (err) {
deferred.reject();
});
}
function get_image_size(img) {
var deferred = Q.defer();
try {
GM(img).size((err, size) => {
if (err)
return deferred.reject(err);
deferred.resolve(size);
});
} catch (err) {
deferred.reject(err);
}
return deferred.promise;
}
@juliovedovatto
Copy link
Author

This method allows to create a resized image with blur background, filling the width x height dimensions.

I took the ideia from http://wizards-toolkit.org/discourse-server/viewtopic.php?t=28035

Needs refactoring, I renamed some variables to fit right in this gist. Contributions are welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment