Skip to content

Instantly share code, notes, and snippets.

@rozboris
Last active August 29, 2015 14:16
Show Gist options
  • Save rozboris/6e0bab8b38ecfcc39cc7 to your computer and use it in GitHub Desktop.
Save rozboris/6e0bab8b38ecfcc39cc7 to your computer and use it in GitHub Desktop.
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);
});
@rozboris
Copy link
Author

See the comments here: harthur/kittydar#23 (comment)

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