-
Notifications
You must be signed in to change notification settings - Fork 3
/
process-image.js
205 lines (170 loc) · 5.9 KB
/
process-image.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
'use strict';
var PromiseA = require('bluebird').Promise
, request = require('request')
, requestA = PromiseA.promisify(request)
, path = require('path')
, fs = PromiseA.promisifyAll(require('fs'))
, gm = require('gm')
;
function process(conf, url, opts) {
var linkpath = path.resolve(conf.originalsFolder, opts.originalFilename)
, height = opts.height
, width = opts.width
, targetFormat = opts.targetFormat
, quality = opts.quality
, ostate = opts.state
, orefresh = opts.refresh // retrieve again from source after n seconds
//, originalFilename = origsum
//, targetBaseName: hash
//, crop
//, filename
;
/*
// TODO: sync .jp{,e}g and .j{,f}if
//sourceFormat = match && match[1].toLowerCase().replace(/(jpe?g|jf?if)/i, 'jpg');
if ('bmp' === sourceFormat) {
targetFormat = targetFormat || 'jpg';
}
*/
function dbGet(key) {
return fs.readFileAsync(key, 'utf8').then(function (str) {
return JSON.parse(str);
});
}
function dbSet(key, value) {
return fs.writeFileAsync(key, JSON.stringify(value, null, ' '), 'utf8');
}
/*
function setFile(key, meta, blob) {
}
function getFile(key, meta) {
}
*/
function saveOriginal(ourl) {
return requestA(ourl, { encoding: null }).spread(function (resp, blob) {
if (resp.statusCode >= 400) {
return PromiseA.reject(resp.statusCode);
}
var image = gm(blob)
;
image.formatAsync = PromiseA.promisify(image.format);
image.sizeAsync = PromiseA.promisify(image.size);
image.writeAsync = PromiseA.promisify(image.write);
return image.formatAsync().then(function(sourceFormat) {
var realpath
, meta
;
sourceFormat = sourceFormat
.toLowerCase()
.replace(/(jpe?g|jf?if)/i, 'jpg')
;
// TODO md5sum the data
meta = {
retrievedAt: Date.now()
, size: blob.length
, format: sourceFormat
, name: opts.originalFilename + '.' + sourceFormat
, url: ourl
, state: ostate // a state param defines the state of the image at original retrieval time is the desired state
, refresh: orefresh
};
realpath = path.resolve(conf.originalsFolder, meta.name);
return fs.writeFileAsync(realpath, blob).then(function () {
return dbSet(linkpath, meta);
}).then(function () {
return { meta: meta, image: image };
});
});
});
}
// TODO put linkpath into db
function retrieveOriginal(ourl, nocache) {
if (nocache) {
return saveOriginal(ourl);
}
// fs.existsAsync is reverse because error fires when exists is true
return fs.existsAsync(linkpath).then(function (/*exists = false*/) {
return saveOriginal(ourl);
}).error(function (exists) {
if (exists.message !== 'true') {
throw exists;
}
return dbGet(linkpath).then(function (meta) {
var expiresIn = orefresh && (orefresh * 1000)
, data
;
data = { meta: meta, image: null };
if (data.meta.state || !expiresIn || (Date.now() - meta.retrievedAt) < expiresIn) {
return data;
}
return saveOriginal(ourl).error(function () {
// if the original can't be retrieved from web, try to get it from disk anyway
return data;
});
}).catch(function () {
return saveOriginal(ourl);
});
});
}
function retrieveResized(data) {
//, realpath = path.resolve(conf.originalsFolder, opts.originalFilename + '.' + data.meta.format)
//data.realpath = path.resolve(conf.imagesFolder, data.filename);
data.filename = opts.targetBaseName + '.' + (targetFormat || data.meta.format);
data.newpath = path.resolve(conf.imagesFolder, data.filename);
return fs.existsAsync(data.newpath).then(function (/*exists = false*/) {
return resizeAndSaveImage(data);
}).error(function(/*exists = true*/) {
return PromiseA.resolve(data);
});
}
function resizeAndSaveImage(data) {
var isNewFormat = targetFormat && (targetFormat !== data.meta.format)
, image
;
if (data.image) {
image = data.image;
} else {
image = gm(path.resolve(conf.originalsFolder, opts.originalFilename + '.' + data.meta.format));
image.formatAsync = PromiseA.promisify(image.format);
image.sizeAsync = PromiseA.promisify(image.size);
image.writeAsync = PromiseA.promisify(image.write);
}
// resize goals:
// if width is given, auto adjust for height
// if height is given, auto adjust for width
// if w and h are given, choose the smallest best fit
// if crop and w and h are given, choose the ratio fit (may add letterboxing)
// always resize before crop?
return image.sizeAsync().then(function (size) {
var newsize
;
//result = image.crop(newW, newH, offsetW, offsetH);
newsize = require('./best-fit').fit(size, width, height);
if (newsize.w !== size.width || newsize.h !== size.height) {
image.resize(newsize.w, newsize.h);
}
if (isNewFormat) {
image.setFormat(targetFormat);
}
if (quality) {
image.quality(quality);
}
return image.writeAsync(data.newpath).then(function () {
return PromiseA.resolve(data);
});
});
}
return retrieveOriginal(url).then(function (data) {
var isNewFormat = targetFormat && (targetFormat !== data.meta.format)
;
if (opts.targetBaseName === opts.originalFilename && !isNewFormat) {
data.filename = opts.originalFilename + '.' + data.meta.format;
data.realpath = path.resolve(conf.originalsFolder, data.filename);
// if no transformation, pass
return PromiseA.resolve(data);
}
// if transformation, transform
return retrieveResized(data);
});
}
module.exports.process = process;