file-upload.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. app
  3. // Angular File Upload module does not include this directive
  4. // Only for example
  5. /**
  6. * The ng-thumb directive
  7. * @author: nerv
  8. * @version: 0.1.2, 2014-01-09
  9. */
  10. .directive('ngThumb', ['$window', function($window) {
  11. var helper = {
  12. support: !!($window.FileReader && $window.CanvasRenderingContext2D),
  13. isFile: function(item) {
  14. return angular.isObject(item) && item instanceof $window.File;
  15. },
  16. isImage: function(file) {
  17. var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
  18. return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
  19. }
  20. };
  21. return {
  22. restrict: 'A',
  23. template: '<canvas/>',
  24. link: function(scope, element, attributes) {
  25. if (!helper.support) return;
  26. var params = scope.$eval(attributes.ngThumb);
  27. if (!helper.isFile(params.file)) return;
  28. if (!helper.isImage(params.file)) return;
  29. var canvas = element.find('canvas');
  30. var reader = new FileReader();
  31. reader.onload = onLoadFile;
  32. reader.readAsDataURL(params.file);
  33. function onLoadFile(event) {
  34. var img = new Image();
  35. img.onload = onLoadImage;
  36. img.src = event.target.result;
  37. }
  38. function onLoadImage() {
  39. var width = params.width || this.width / this.height * params.height;
  40. var height = params.height || this.height / this.width * params.width;
  41. canvas.attr({ width: width, height: height });
  42. canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
  43. }
  44. }
  45. };
  46. }]);