UNPKG

2.33 kBJavaScriptView Raw
1var fs = require("fs"),
2 path = require("path"),
3 sizeOf = require('image-size'),
4 utils = require("./utils");
5
6//
7
8var Image = function( options ){
9
10 this.options = options;
11
12};
13
14Image.prototype = {
15
16 compile: function(source, callback) {
17
18 var self = this;
19 // gather data
20 var data = {
21 source: source,
22 name: this.options.name || utils.filename( this.options.files ),
23 dir: utils.tmpDir(),
24 ext: path.extname( source )
25 }
26 var ratio = this.options.ratio || "auto"; // dynamically read media dimensions instead?
27 var sizes = this.options.image.sizes[ratio];
28 var original = data.dir + data.name + data.ext;
29 // copy original file to temp dir
30 fs.createReadStream( source ).pipe(fs.createWriteStream( original ))
31 .on("finish", function(){
32 // start grunt
33 var options = {
34 gruntfile : path.normalize( __dirname+'/../gruntfile.js'),
35 responsive_images: {
36 encode:{
37 options: {
38 sizes: sizes,
39 engine: "im", // using ImageMagick by default...
40 createNoScaledImage: true, // never create scaled up image (flag set wrong?)
41 gaussianBlur: 0.05,
42 quality: 60
43 },
44 files: [{
45 //expand: true,
46 src: [ original ],
47 cwd: data.dir,
48 dest: original // destination path is used to get the file extension, why?
49 }]
50 }
51 }
52 };
53
54 // new instance of grunt...
55 var grunt = require("grunt");
56
57 grunt.initConfig( options );
58
59 // execute tasks...
60 grunt.tasks(["responsive_images"], options, function(){
61 //console.log("Grunt.js Tasks Completed!");
62 callback( data );
63 });
64
65 });
66
67 },
68
69 ratio: function( file ){
70 // get image dimensions
71 var dimensions = sizeOf( file );
72 var ratio = dimensions.width / dimensions.height;
73 // find a standard ratio
74 if( ratio == 16/9 ) return "16:9";
75 if( ratio == 4/3 ) return "4:3";
76 // fallback?
77 return false;
78 }
79
80}
81
82
83module.exports = function( file, callback ){
84 var options = this.options;
85 var self = this;
86 // new instance of the video class
87 var image = new Image( options );
88 // get (auto-set) ratio
89 var ratio = image.ratio( file );
90 if( ratio ) image.options.ratio = ratio;
91 image.compile( file, function( data ){
92 // back to the main lib to store the files...
93 self.onCompileComplete( data, callback );
94 });
95};