-
-
Save rozboris/6e0bab8b38ecfcc39cc7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('follow-redirects').http; | |
var express = require('express'); | |
var request = require('request'); | |
var url = require('url'); | |
var fs = require('fs'); | |
var Canvas = require('canvas'); | |
var kittydar = require('kittydar'); | |
var sharp = require('sharp'); | |
var app = express(); | |
var server = http.createServer(app); | |
app.get('*', function(req, res) { | |
try{ | |
var address = req.query.url; | |
if(!address){ | |
res.json({ | |
'message': 'Example: /?url=http://url-to-image.png', | |
}); | |
return; | |
} | |
console.log('address is ' + address); | |
request({ | |
method: 'GET', | |
url: address, | |
encoding: null, | |
}, function (error, response, body) { | |
if (!error && response.statusCode == 200) { | |
var image = new Canvas.Image; | |
image.onload = function(){ | |
console.log('loaded image ' + address, image.width, image.height); | |
var canvas = new Canvas(image.width, image.height); | |
var ctx = canvas.getContext('2d'); | |
ctx.drawImage(image, 0, 0, image.width, image.height); | |
try{ | |
var cats = kittydar.detectCats(canvas); | |
res.json({ | |
'result': cats | |
}); | |
}catch(err){ | |
res.status(500).json({ | |
'error': ''+err, | |
}); | |
} | |
}; | |
image.onerror = function(err, err1){ | |
console.log(err); | |
res.status(500).json({ | |
'error': ''+err, | |
'comment': 'Error when loading the image', | |
}); | |
}; | |
try{ | |
var buffer_png = sharp(body).toFormat('png').toBuffer(function(err, outputBuffer) { | |
if (err) { | |
console.log('Error in sharp library', err); | |
res.status(500).json({ | |
'comment': 'Error in sharp library while opening or converting to png', | |
'error': err+'' | |
}); | |
}else{ | |
image.src = outputBuffer; | |
} | |
}); | |
}catch(err){ | |
console.log('Error in sharp library', err); | |
res.status(500).json({ | |
'comment': 'Error in sharp library while opening or converting to png', | |
'error': err+'' | |
}); | |
} | |
}else{ | |
console.log('Error in fetching document', error); | |
res.status(500).json({ | |
'comment': 'Error when fetching document', | |
'error': error+'' | |
}); | |
} | |
}) | |
}catch(err){ | |
console.log('General error somewhere', err); | |
res.status(500).json({ | |
'error': err, | |
'comment': 'General exception in outer try-catch', | |
}); | |
} | |
}); | |
server.listen(1234, 'localhost'); | |
server.on('listening', function() { | |
console.log('Express server started on port %s at %s', server.address().port, server.address().address); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the comments here: harthur/kittydar#23 (comment)