1
votes

With this script i can tile my (4096x2048) images into 32 tiles(512x512). I would like to give a "X, Y, Z" cordinate to each exported image.

For now i would like to keep Z as 0 always.

Example:

  • output-1-0-0.jpg
  • output-1-1-0.jpg

    var http = require("http");
    var im = require("imagemagick"); 
    
    var server = http.createServer(function(req, res) {
    
      im.convert(['img.jpg','-crop','512x512','output.jpg'], function(err) {
        if(err) { throw err; }
        res.end("Image crop complete");
      });
    
    }).listen(8080);
    

And beside that, Sorry for this dumb question im newby to nodejs, instead of giving the image name into the script, can i call as GET request to crop and get all image as a service ?

Thanks in advance

1

1 Answers

1
votes

I don't think that imagemagick can handle GET requests. But what you can do is to save the image coming from a GET request into a local file, and then call imagemagick to crop this image into separate tiles.

A very good http request library for node.js is request.

It has a pipe() method which pipe any response to a file stream:

http.createServer(function (req, resp) {
  if (req.url === '/img.jpg') {
    if (req.method === 'GET' || req.method === 'HEAD') {
      var r= request.get('http://localhost:8008/img.jpg')
      .on('error', function(err) {
        console.log(err)
      }).pipe(fs.createWriteStream('doodle.png')) // pipe to file
    }
  }
})

By assigning the response to a variable you can check if the pipe operation has been completed, if so you can call the imagemagick method for the cropping operations.

Streams are event emitters so you can listen to certain events, like an end event.

r.on('end', function() {
    im.convert(['img.jpg','-crop','512x512','output.jpg'], function(err) {
    if(err) { throw err; }
    res.end("Image crop complete");
  });
});

Here is the complete code (but not tested). This is only for guidance.

http.createServer(function (req, resp) {
  if (req.url === '/img.jpg') {
    if (req.method === 'GET' || req.method === 'HEAD') {
      var r = request.get('http://localhost:8008/img.jpg')
      .on('error', function(err) {
        console.log(err)
      }).pipe(fs.createWriteStream('doodle.png')) // pipe to file

      r.on('end', function() {
        im.convert(['img.jpg','-crop','512x512','output.jpg'], function(err) {
            if(err) { throw err; }
            res.end("Image crop complete");
          });
        });
    }
  }
})