Skip to content

Instantly share code, notes, and snippets.

@fatuhoku
Forked from lukejohnjones/parse_thumbnail
Created November 17, 2015 21:51
Show Gist options
  • Save fatuhoku/e4d893288a2f36a6f341 to your computer and use it in GitHub Desktop.
Save fatuhoku/e4d893288a2f36a6f341 to your computer and use it in GitHub Desktop.
Parse.com thumbnail creation retaining aspect ratio
var Image = require("parse-image");
Parse.Cloud.beforeSave("_User", function(request, response) {
var user = request.object;
if (!user.get("profilePhoto")) {
response.error("Users must have a profile photo.");
return;
}
if (!user.dirty("profilePhoto")) {
// The profile photo isn't being modified.
response.success();
return;
}
Parse.Cloud.httpRequest({
url: user.get("profilePhoto").url()
}).then(function(response) {
var image = new Image();
return image.setData(response.buffer);
}).then(function(image) {
// Crop the image to the smaller of width or height.
var minSize = Math.min(image.width(), image.height());
if(minSize === image.width())
{
return image.scale({
width: 160,
height: 160*image.height()/image.width()
});
}
else
{
return image.scale({
width: 160*image.width()/image.height(),
height: 160
});
}
}).then(function(image) {
// Make sure it's a JPEG to save disk space and bandwidth.
return image.setFormat("JPEG");
}).then(function(image) {
// Get the image data in a Buffer.
return image.data();
}).then(function(buffer) {
// Save the image into a new file.
var base64 = buffer.toString("base64");
var cropped = new Parse.File("thumbnail.jpg", { base64: base64 });
return cropped.save();
}).then(function(cropped) {
// Attach the image file to the original object.
user.set("profilePhotoThumbnail", cropped);
}).then(function(result) {
response.success();
}, function(error) {
response.error(error);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment