Parse Cloud Code

Say you have a large number of images of different sizes on Parse. You’re downloading them for display in a table or any other type of view. Of course, you definitely need the size of each image, while you are waiting for the download of each image. Something like this isn’t directly possible with PFFile untill the getData call is finished. This means that you need to download the complete image to know the size of the image and so, if you want to render a temporary placeholder or something in place, you have to do a default size and live with the slight annoyance that changing the size later would cause.

A much better way to deal with this is to compute the size of the image when it is uploaded to parse. Rather than putting this on the client side which is prone to all kinds of errors and miscalculations, it is much better to have it in one place, the back end and it is really easy to do with Parse Cloud Code. Its really easy to get started, you just need to install the command line tool, and set up the cloud code with parse new.

Let’s see how we can compute the image size with Cloud Code. We will use the afterSave hook to get a callback which is invoked everytime a new Image (class name) object is saved. Assuming that we have a column of type PFFile at the path imageFile, here’s how we can find teh size of the file and store it in width and height columns in the Image object.

// Updates image width and height after save
Parse.Cloud.afterSave("Image", function(request) {
  var imageObject = request.object;
  var imageFile = imageObject.get('imageFile');
  var Image = require("parse-image");
    url: imageFile.url(),
    success: function(response) {
        // The file contents are in response.buffer.
        var image = new Image();
        return image.setData(response.buffer, {
            success: function() {
              imageObject.set('width', image.width());
              imageObject.set('height', image.height());
            error: function(error) {
              // The image data was invalid.
    error: function(error) {
      // The networking request failed.
      console.error("Cannot update image dimensions" + error.code + " : " + error.message);

Once you are done, just deploy the code with parse deploy and you are all set. Try saving some images! You should now automatically get the width and height in the respective columns.