(function () { 'use strict'; angular.module('streamApp') /** * The ng-thumb directive * @author: nerv * @version: 0.1.2, 2014-01-09 */ .directive('ngThumb', ['$window', function ($window) { var helper = { support: !!($window.FileReader && $window.canvasRenderingContext2D), isFile: function (item) { return angular.isObject(item) && item instanceof $window.File; }, isImage: function (file) { var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; } }; return { restrict: 'A', template: '', link: function (scope, element, attributes) { if (!helper.support) return; var params = scope.$eval(attributes.ngThumb); if (!helper.isFile(params.file)) return; if (!helper.isImage(params.file)) return; var canvas = element.find('canvas'); var reader = new FileReader(); reader.onload = onLoadFile; reader.readAsDataURL(params.file); function onLoadFile(event) { var img = new Image(); img.onload = onLoadImage; img.src = event.target.result; } function onLoadImage() { var self = this; var image = { width: params.width || self.width / self.height * params.height, height: params.height || self.height / self.width * params.width }; var width = params.width || this.width / this.height * params.height; var height = params.height || this.height / this.width * params.width; loadImage.parseMetaData( params.file, function (data) { let orientation = data.exif ? data.exif.get('Orientation') || 1 : 1; draw(orientation, image, self); }); } function draw(orientation,image,self) { var rotation = 0; var translation = { width: 0, height: 0 }, render = { width: image.width, height: image.height } switch (orientation) { case 8: rotation = (Math.PI / -2); render.width = image.height; render.height = image.width; translation.height = image.width; break; case 3: rotation = (Math.PI); translation.height = image.height; translation.width = image.width; break; case 6: rotation = (Math.PI / 2); render.width = image.height; render.height = image.width; translation.width = render.width; break; } var can = canvas[0]; can.width = render.width; can.height = render.height; var ctx = can.getContext("2d"); ctx.translate(translation.width, translation.height); //let's translate ctx.rotate(rotation); //increment the angle and rotate the image ctx.drawImage(self, 0, 0, image.width, image.height); //draw the image ;) } function flip(i) { var t = i.width; i.width = i.height; i.height = t; } } }; }]); }());