Skip to content

Using Imagemagick in Cloud Code #648

Closed

Description

@oyvindvol

Hi,

This is not really an issue with Parse-Server, rather a cry for help with using Imagemagick instead of Parse-Image in my cloud code functions. Can anyone point me in the right direction to achieve the same as expressed in my old cloud code:

Parse.Cloud.beforeSave("TheClass", function(request, response) {
  var theObject= request.object;

  Parse.Cloud.httpRequest({
    url: theObject.get("img").url()
  }).then(function(response) {
    var image = new Image();
    return image.setData(response.buffer);
  }).then(function(image) {
    var currentWidth = image.width();
    var currentHeight = image.height();
    var ratio = currentHeight / currentWidth;
    if (currentWidth > 640) {
      return image.scale({
        width: 640,
        height: 640 * ratio
      });
    } else {
      return image;
    }
  }).then(function(image) {
    return image.setFormat("JPEG");
  }).then(function(image) {
    return image.data();
  }).then(function(buffer) {
    var base64 = buffer.toString("base64");
    var cropped = new Parse.File("thumb.jpeg", { base64: base64 });
    return cropped.save();
  }).then(function(cropped) {
    theObject.set("thumb", cropped);
  }).then(function(result) {
    response.success();
  }, function(error) {
    response.error(error);
  });
});

Any help will be much appreciated!

Activity

  1. oyvindvol commented on Feb 25, 2016

    @oyvindvol
    Author

    After adding parse-image to my package.json the module is found.

    But now I get this error:

    [Error: Command failed: identify.im6: no decode delegate for this image format `/tmp/magick-x4qqyfba'
    
  2. oyvindvol commented on Feb 25, 2016

    @oyvindvol
    Author

    Ok, thanks a lot so far @flovilmart!

    I tried console.logging the url to my uploaded ParseFile, console.log(theObject.get("img").url());. The url was http, not https. Then i ran this command in the heroku bash identify -verbose <URL-TO-FILE>, and there the identify seemed to work fine at least.

    identify -verbose http://<app>/parse/files/sv78uRNzD4RPUKW9
    
    Image: 5ef1d74591c83c189609957ee1f18860_portal.PNG
      Base filename: 5ef1d74591c83c189609957ee1f18860_portal.PNG
      Format: PNG (Portable Network Graphics)
      Class: DirectClass
      Geometry: 2438x1400+0+0
      Resolution: 75.59x75.59
    ...
    ...
    and so on
    
  3. flovilmart commented on Feb 25, 2016

    @flovilmart
    Contributor

    Is your response.buffer set?

  4. oyvindvol commented on Feb 25, 2016

    @oyvindvol
    Author

    Yes

  5. flovilmart commented on Feb 25, 2016

    @flovilmart
    Contributor

    Uhm... that's very very odd indeed. Did you try on you local machine, see if it's heroku related or something else?

  6. flovilmart commented on Feb 25, 2016

    @flovilmart
    Contributor

    You should probably open an issue on parse-image instead of there. Closing for now.

  7. oyvindvol commented on Feb 25, 2016

    @oyvindvol
    Author

    Well, initially this issue was about using the recommended Imagemagick in parse server cloud code. I am still interested in examples on that though..

  8. flovilmart commented on Feb 25, 2016

    @flovilmart
    Contributor

    OK, can you post an issue on parse-image I'll re-open in that case.

  9. simonbengtsson commented on Feb 25, 2016

    @simonbengtsson
    Contributor

    I used jimp to replace parse-image when I migrated our app. It is written entirely in JavaScript for Node so no external dependencies needed (no special install on heroku or windows). It probably has worse performance than imagemagick, but I have yet to run any benchmarks. We are scaling a lot of images in our app however and so far it looks promising.

  10. oyvindvol commented on Feb 26, 2016

    @oyvindvol
    Author

    @simonbengtsson That looks lightweight and good. Are you using jimp to e.g. save thumbnails via cloud code? I am having trouble getting that work. With the code provided below, everything seems OK, and the thumb is saved on the "Message" object, but viewing the thumb in the browser with the file URL is not working.

    var Jimp = require("jimp");
    
    Parse.Cloud.beforeSave("Message", function(request, response) {
      var obj = request.object;
    
      if (!obj .get("img")) {
        response.success();
        return;
      }
    
      Jimp.read(obj.get("img").url())
      .then(function(image) {
        var currentWidth = image.bitmap.width;
        var currentHeight = image.bitmap.height;
        var ratio = currentHeight / currentWidth;
        if (currentWidth > 640) {
          return image.resize(640, 640 * ratio)
        } else {
          return image;
        }
      })
      .then(function(image) {
        console.log("### 1");
        var base64 = image.hash();
        var cropped = new Parse.File("thumb.jpeg", { base64: base64 });
        return cropped.save();
      })
      .then(function(cropped) {
        console.log("### 2");
        obj.set("thumb", cropped);
      })
      .then(function(result) {
        console.log("### 3");
        response.success();
      }, function(error) {
        console.log("### 4 ERROR: " + error);
        response.error(error);
      })
      .catch(function (err) {
        console.log("### 5 ERROR: " + err);
      });
    });
    
  11. simonbengtsson commented on Feb 26, 2016

    @simonbengtsson
    Contributor

    Yes we are generating thumbnails in cloud code using jimp. Your issue is probably that the string from image.hash() cannot be used as data for parse files. Try something like this instead:

    return new Parse.Promise((resolve, reject) => {
        image.resize(100, 100).getBuffer(Jimp.MIME_JPEG, (err, buffer) => {
            if (err) return reject(err);
            var file = new Parse.File('picture.jpg', {base64: buffer});
            resolve(file.save());
        });
    });
  12. oyvindvol commented on Feb 29, 2016

    @oyvindvol
    Author

    @simonbengtsson Thanks! :) That worked..

  13. nitrag commented on Mar 3, 2016

    @nitrag

    Since it took me several hours to get this correct I'm posting here so the next guy has an easier time:

    Parse.Cloud.beforeSave("Photos", function(request, response) {
        Parse.Cloud.useMasterKey();
    
        createThumbnail(request.object.get("Image").url(), 360, 360).then(function(shrunk) {
            request.object.set("ImageThumbnail", shrunk);
            console.log("Thumbnail generated/added: " + JSON.stringify(shrunk));
        }).then(function(result) {
                response.success("thumbnail saved");
            }, function(error) {
                response.error("thumbnail creation error: " + error.code + "("+ error.message + ")");
        });
    });
    function createThumbnail(url, maxWidth, maxHeight){
        var Jimp = require("jimp");
        Parse.Cloud.useMasterKey();
        if(url === ""){
            console.log("url empty");
            return;
        }
    
        console.log("Generating Thumbnail...");
        return Jimp.read(url).then(function(image) {
            console.log("Buffer read, resizing...");
            var ratioX = maxWidth / image.bitmap.width; 
            var ratioY = maxHeight / image.bitmap.height;
            var ratio = Math.min(ratioX, ratioY);
    
            var w = image.bitmap.width * ratio;
            var h = image.bitmap.height * ratio;
    
            return image.resize(w, h );
        }).then(function(image) {
            console.log("Resized, setting quality...");
            return image.quality(90);
        }).then(function(image) {
            console.log("Quality set, return buffer");
            var promise = new Parse.Promise();
                image.getBuffer(Jimp.MIME_JPEG, function(err, buffer){
                    if (err) return promise.reject(err);
                    promise.resolve(buffer);
                });
            return promise;
        }).then(function(buffer) {
            console.log("Buffer returned, creating Parse File");
            var shrunk = new Parse.File("thumbnail.jpg", { base64: buffer }, "image/jpeg");
            return shrunk.save();
        }).then(function(shrunk) {
                return shrunk;
            }, function(error) {
                console.log("thumbnail generation error: " + error.code + "("+ error.message + ")");
                return;
        });
    
    }
    
  14. 6thfdwp commented on May 14, 2016

    @6thfdwp
    Contributor

    Thanks for sharing this pure js image module, here is the benchmarks I found for jimp in comparison with other libraries.
    lovell/sharp#275 (comment)

    It seems enough for common image processing cases.

  15. majidhassan commented on May 29, 2016

    @majidhassan

    @flovilmart I tried your parse-image module on Heroku for a simple thumbnail generation. I did not need to change a single line of code, only added "parse-image": "~0.1.1" in my package.json dependencies, and it works fine so far.

    Great job!

  16. rickkrauland commented on Aug 7, 2016

    @rickkrauland

    @nitrag Thanks for your post. Fwiw, I had to add a buffer.toString conversion before I could get everything to work.

    var base64 = buffer.toString("base64");
    var shrunk = new Parse.File("thumbnail.jpg", { base64: base64 }, "image/jpeg");         
    return shrunk.save({useMasterKey: true});
    
  17. parkej60 commented on Sep 23, 2016

    @parkej60

    This all seems to be working great for me using jimp until the part where I try to set it to the object in the beforeSave hook. I see the images showing up in S3 and it comes back correctly. I have other attributes that are getting set correctly as well. It is just the 'pictureThumbnail' that isn't. For some reason it just seems as if it's not updating the request.object. @rickkrauland Was there something you had to do different then what is documented in @nitrag 's example?

    createThumbnail(url, 300, 300).then(function(shrunk) {
                restaurant.set("pictureThumbnail", shrunk);
                console.log("Thumbnail generated/added: " + JSON.stringify(shrunk));
            }).then(function(result) {
                    response.success("thumbnail saved");
                }, function(error) {
                    response.error("thumbnail creation error: " + error.code + "("+ error.message + ")");
            });
    
  18. parkej60 commented on Sep 23, 2016

    @parkej60

    So... turns out that response.success doesn't want a string sent along with it. I removed "thumbnail saved" from response.success() and it worked.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions