Skip to content

Instantly share code, notes, and snippets.

@metalaureate
Created September 20, 2016 16:50
Show Gist options
  • Save metalaureate/252cd6fc7ffea1027d5f3acc08c7ca20 to your computer and use it in GitHub Desktop.
Save metalaureate/252cd6fc7ffea1027d5f3acc08c7ca20 to your computer and use it in GitHub Desktop.
function fixOrientation(url, cb) {
// this function takes an s3 image
// check if it needs to be rotated
// if so, it creates a new version rotated
// uploads to S3
// and passes the url back
var exif = require('exif').ExifImage;
var easyimg = require('easyimage');
var path = require('path'), fs = require('fs-extra'), request = require('request');
sails.log.debug('checking exif tags for rotation');
var filename = path.basename(url);
var pic = {
source_url: url,
dest_dir: sails.config.appPath + "/.tmp/" + filename
};
pic.stream = fs.createWriteStream(pic.dest_dir);
sails.log.debug(url, 'downloading to .tmp');
pic.stream.on('close', function () {
sails.log.debug('photo downloaded ' + pic.source_url);
try {
new exif(pic.dest_dir, function (error, exifData) {
if (error) {
console.log('Error: ' + error.message);
return cb(error, url);
} else {
console.log(exifData); // Do something with your data!
var orientation, width, height;
try {
orientation = exifData.image.Orientation;
width = exifData.exif.ExifImageWidth;
height = exifData.exif.ExifImageHeight;
} catch (e) {
// sails.log.error(e);
return cb(e, url);
}
var rot = null;
switch (orientation) {
case 3:
rot = 180;
break;
case 6:
rot = 90;
break;
case 8:
rot = 270;
break;
}
if (rot) {
sails.log.debug(url, 'needs rotating ' + rot + ' degrees');
var new_filename = 'reoriented_' + filename;
var new_dst = sails.config.appPath + "/.tmp/" + new_filename;
easyimg.rotate({
src: pic.dest_dir,
dst: new_dst,
degree: rot
}).then(function (result) {
sails.log.debug(url, 'created new rotated image', result);
S3.uploadS3(new_dst, new_filename,
function (err, res) {
sails.log.debug('res', res);
sails.log.debug('putting photo to S3 ' + new_filename);
if (err) {
throw err;
}
//delete local files when done
fs.unlinkSync(new_dst); //clean up
fs.unlinkSync(pic.dest_dir);
return cb(null, (res) ? res.Location : null);
});
}, function (error) {
sails.log.error(error);
}).finally(function (err) {
sails.log.info('we got to finally', err)
if (err) {
sails.log.error(error);
}
// return cb(null, (res) ? res.Location : null);
})
} else {
return cb(null, url);
}
}
});
} catch (error) {
console.log('Error: ' + error.message);
cb(error, url)
}
});
request(pic.source_url).pipe(pic.stream); //refers back
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment