Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save edwardhotchkiss/3984636 to your computer and use it in GitHub Desktop.
Save edwardhotchkiss/3984636 to your computer and use it in GitHub Desktop.
Use GM Module (Graphics Magick) for Node.js to center an image on a white background canvas
var gm = require('gm');
var canvasWidth = 248;
var canvasHeight = 389;
gm(__dirname + '/original.jpg').size(function(error, size) {
if (error) {
console.error(error);
} else {
// current image size
var imageWidth = size.width;
var imageHeight = size.height;
// center placement
var x = (canvasWidth / 2) - (imageWidth / 2);
var y = (canvasHeight / 2) - (imageHeight / 2);
console.log(x, y);
this.background('#ffffff')
.resize(imageWidth, imageHeight)
.gravity('Center')
.extent(canvasWidth, canvasHeight)
.write(__dirname + '/test.jpg', function(error) {
if (error) {
console.error(error);
} else {
console.log(this.outname);
};
})
}
});
@teknologist
Copy link

Thx!

@aramirez92
Copy link

Thanks

@njnm
Copy link

njnm commented Jul 21, 2016

Really thanks man. It helped me a lot

@btleffler
Copy link

Sorry if this is a stupid question, but what is the point of calculating x and y?

@benallfree
Copy link

@btleffler Not needed in this example because .gravity('center') does the work.

@SergeyMaas
Copy link

Thk!

@maximilian-lindsey
Copy link

Thanks a lot!

@RonaldoHVL
Copy link

Thanks! this was really helpful!!

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