Skip to content

Instantly share code, notes, and snippets.

@serby
Created March 27, 2013 15:01
Show Gist options
  • Select an option

  • Save serby/5254880 to your computer and use it in GitHub Desktop.

Select an option

Save serby/5254880 to your computer and use it in GitHub Desktop.
var
gm = require('gm'),
properties = require('../../properties').getProperties(),
fs = require('fs');
module.exports.createImageManager = function() {
function resizeAndCrop(hash, filename, width, height, crop, callback) {
var
newCachedLocation,
currentFileLocation = properties.dataPath + hash + '/' + filename;
console.log('###', currentFileLocation);
gm(currentFileLocation).size(function(error, value) {
var
sourceWidth = value.width,
sourceHeight = value.height,
widthAspectRatio = width / sourceWidth,
heightAspectRatio = height / sourceHeight,
destinationWidth = width,
destinationHeight = height,
widthOffset = (value.width / 2) - (width / 2),
heightOffset = (value.height / 2) - (height/2);
if (crop) {
newCachedLocation = properties.cachePath + '/' + hash + '/' + width + 'x' + height + 'c' + '_' + filename;
console.log('cropping');
if (widthAspectRatio > heightAspectRatio) {
sourceHeight = height;
sourceWidth = width;
} else {
sourceHeight = height;
sourceWidth = width;
}
console.log(destinationWidth, destinationHeight, widthOffset, heightOffset);
gm(currentFileLocation).colorspace('rgb').crop(destinationWidth, destinationHeight, widthOffset, heightOffset).write(newCachedLocation, function(error) {
if (error) {
callback(error, null);
} else {
callback(null, newCachedLocation);
}
});
} else {
newCachedLocation = properties.cachePath + '/' + hash + '/' + width + 'x' + height + '_' + filename;
console.log('shrinking');
if (widthAspectRatio > heightAspectRatio) {
destinationWidth = sourceWidth * heightAspectRatio;
destinationHeight = sourceHeight * heightAspectRatio;
} else {
destinationWidth = sourceWidth * widthAspectRatio;
destinationHeight = sourceWidth * widthAspectRatio;
}
console.log(widthAspectRatio, heightAspectRatio, destinationWidth, destinationHeight);
gm(currentFileLocation).colorspace('rgb').resize(destinationWidth, destinationHeight).write(newCachedLocation, function(error) {
if (error) {
callback(error, null);
} else {
callback(null, newCachedLocation);
}
});
}
});
}
return {
resizeAndCrop: resizeAndCrop
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment