-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathglimpse.js
More file actions
376 lines (291 loc) · 10.2 KB
/
glimpse.js
File metadata and controls
376 lines (291 loc) · 10.2 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
var glimpse = function(document){ "use strict";
// # Initialise
// Set a class-name when a .canvas() or .image() are used.
var classNames = {
base: "preview", // Added to every element
monochrome: "monochrome", // Added to monochrome images
};
// WARNING: Changing following variables might break the library, proceed with caution.
var type = "image/jpeg";
var pool = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
var separateData = ",";
var separateSize = ":";
var tagImg = "img";
var tagCanvas = "canvas";
var hexPrefix = "#";
var monoPrefix = "m";
// Generate all possible shorthand hex color combinations (#000 – #fff, 4.096 in total).
var hexIndex = function(string){ // "0123456789ABCDEF"
var length = string.length;
var result = [];
for (var a = 0; a < length; ++a){
for (var b = 0; b < length; ++b){
for (var c = 0; c < length; ++c){
result.push([ string[a], string[b], string[c] ].join(""));
}
}
}
return result;
}(pool.substr(0, 16));
// Generate a two-byte key for each value in the hexIndex.
var keyIndex = function(string){
var length = string.length;
var result = [];
for (var a = 0; a < length; ++a){
for (var b = 0; b < length; ++b){
result.push([ string[a], string[b] ].join(""));
}
}
return result;
}(pool);
// Generate a map to pair each key with its hex value and vice versa.
var map = function(hexMap, keyMap){
for (var i = 0; i < 4096; ++i){
var hex = hexIndex[i], key = keyIndex[i];
hexMap[hex] = key;
keyMap[key] = hex;
}
return { hex: hexMap, key: keyMap };
}({}, {});
// Expose public methods
return {
create: encodeImage,
base64: imageToBase64,
canvas: imageToCanvas,
image: imageToImg,
meta: getImageMeta,
get support(){ return !!getContext(createImage(tagCanvas)) }
};
// # Public methods
// Load an image source URI/URL and generate a data-string from its imageData using canvas.
function encodeImage(source, callback, quality, monochrome){
var image = createImage(tagImg);
image.onload = function(){
var width = image.naturalWidth;
var height = image.naturalHeight;
var scaled = resize(width, height, quality);
var color = null;
var imageData = getData(image, scaled.width, scaled.height).data;
var length = imageData.length;
var i = 0;
var result = []; // Here go the keys
var a = 0, b = 0, c = 0;
var colorIndex = [ 0, 0, 0 ]; //
var count = 0; //
if (!monochrome){
for (i = 0; i < length; i += 4){
a = imageData[i ]; colorIndex[0] += a;
b = imageData[i+1]; colorIndex[1] += b;
c = imageData[i+2]; colorIndex[2] += c;
if (monochrome !== false) monochrome = a === b && b === c;
result[count++] = channelToKey(a, b, c);
}
color = getAverageColor(colorIndex, count);
}
if (monochrome === true){
result = [], count = 0; // reset image
// scaled.width += 1000; // map preview width to private key-range
var getAverage = color === null; // c
for (i = 0; i < length; i += 12){
var trio = [];
for (var pixel = 0; pixel < 12; pixel += 4){
a = imageData[i+pixel ]; // r
b = imageData[i+pixel+1]; // g
c = imageData[i+pixel+2]; // b
trio.push(Math.round((a + b + c) / 3)); // push grayscale value
if (getAverage && a){
colorIndex[0] += a; // r
colorIndex[1] += b; // g
colorIndex[2] += c; // b
}
}
result[count++] = channelToKey(trio[0], trio[1], trio[2]);
}
color = getAverage ? getAverageColor(colorIndex, count * 4) : color;
}
// Compose the data-string and pass it to a callback function.
result = [
(monochrome ? monoPrefix : hexPrefix) + color, // Prefix with Average color...
width, separateSize, height, separateData, // and dimensions.
keyIndex[scaled.width], result.join("") // Image data
].join("");
callback(result, {
width: width,
height: height,
color: hexPrefix + color,
black: hexPrefix + hexToMonochrome(color),
monochrome: monochrome
});
}
if (!isBase64(source)) image.crossOrigin = "anonymous";
image.src = source;
}
// Pass a base64-encoded image to the callback
function imageToBase64(string, callback, width, height){
decodeImage(string, callback, width, height);
}
// Pass a canvas-element image to the callback
function imageToCanvas(string, callback, width, height){
decodeImage(string, callback, width, height, tagCanvas);
}
// Pass an img-element to the callback
function imageToImg(string, callback, width, height){
decodeImage(string, callback, width, height, tagImg);
}
// Draw a base64-encoded jpeg-image from a data-string created by preview.encode() using canvas.
function decodeImage(input, callback, width, height, element){
// If a base64-encoded image is passed at this stage its expected to be optimised so it
// won’t affect its quality or resolution.
if (isBase64(input)) return encodeImage(input, function(source){
decodeImage(source, callback, element, width, height);
}, false);
// else...
// Extract image data from the string parameter.
var source = input.split(separateData);
var data = source[1].match(/.{1,2}/g);
// Extact meta data from the source prefix.
var meta = getImageMeta(source[0]);
if (!isNaN(width)){
if (!isNaN(height)) meta.height = height;
else meta.height = Math.round(meta.height * width / meta.width);
meta.width = width;
}
var previewWidth = keyIndex.indexOf(data.shift());
var previewHeight = data.length / previewWidth; // calculate the preview’s height
if (meta.monochrome) previewHeight = 0|previewHeight * 3; // compensate for the smaller data.length
// Prepare a html canvas.
var canvas = createImage(tagCanvas, previewWidth, previewHeight);
var imageData = createData(canvas, previewWidth, previewHeight);
var length = imageData.data.length;
var i = 0;
// Set the canvas image data.
var index = 0, current = 0;
if (meta.monochrome) for (i = 0; i < length; i += 12){
current = keyToChannel(data[index++]);
var a = current[0], b = current[1], c = current[2];
imageData.data[i ] = a;
imageData.data[i+1] = a;
imageData.data[i+2] = a;
imageData.data[i+3] = 255;
imageData.data[i+4] = b;
imageData.data[i+5] = b;
imageData.data[i+6] = b;
imageData.data[i+7] = 255;
imageData.data[i+8] = c;
imageData.data[i+9] = c
imageData.data[i+10] = c;
imageData.data[i+11] = 255;
}
else for (i = 0; i < length; i += 4){
current = keyToChannel(data[index++]);
imageData.data[i ] = current[0];
imageData.data[i+1] = current[1];
imageData.data[i+2] = current[2];
imageData.data[i+3] = 255;
}
setData(canvas, imageData);
// Load and redraw the canvas image to its given dimensions,
// then pass it to the callback as a base64 encoded jpeg-image.
var image = createImage(tagImg);
image.onload = function(){
var result = drawImage(image, meta.width, meta.height);
if (element !== tagCanvas) result = result.toDataURL(type);
if (element){
if (element === tagImg){
element = createImage(element, meta.width, meta.height);
element.src = result;
result = element;
}
var className = classNames.base;
if (meta.monochrome) className += " " + classNames.monochrome;
result.className = className;
}
callback(result, meta);
}
image.src = canvas.toDataURL(type);
}
// Extract meta data from an encoded string.
function getImageMeta(string, key){
string = string.split(separateData)[0];
var dimensions = string.substr(7).split(separateSize);
var color = string.substr(1, 6);
var monochrome = string[0] === monoPrefix;
var object = {
width: dimensions[0],
height: dimensions[1],
color: hexPrefix + color,
black: hexPrefix + hexToMonochrome(color),
monochrome: monochrome
};
return typeof key === "string" ? object[key] : object;
}
// # Private functions
// Utilities
function isBase64(value){ return /^data:image/.test(value) }
function limit(value, min, max){ return value < min ? min : value > max ? max : value }
function resize(width, height, quality){
if (quality !== false){
quality = !isNaN(quality) && limit(quality, 1, 100) || 50;
var resolution = quality / 1500;
var treshold = quality * 1.28;
var ratio = width / height;
if (ratio > 1){
width = Math.round(limit(width * resolution, 6, treshold));
height = Math.round(width / ratio);
}
else {
height = Math.round(limit(height * resolution, 6, treshold));
width = Math.round(height * ratio);
}
}
return { width: width, height: height };
}
// Color
function channelToKey(a, b, c){
return map.hex[get(a) + get(b) + get(c)];
function get(value){ return pool[Math.round(value / 17)] }
}
function keyToChannel(key){
var hex = map.key[key];
return [ get(hex[0]), get(hex[1]), get(hex[2]) ];
function get(value){ return parseInt(value + value, 16) }
}
function getAverageColor(average, index){
index = !isNaN(index) ? index : 1;
var a = average[0] / index, b = average[1] / index, c = average[2] / index;
return channelToHex(a) + channelToHex(b) + channelToHex(c);
}
function channelToHex(channel) {
var hex = Math.round(channel).toString(16);
return hex.length === 1 ? 0 + hex : hex;
}
function hexToMonochrome(hex){
hex = hex.match(/.{1,2}/g);
hex = parseInt(hex[0], 16) + parseInt(hex[1], 16) + parseInt(hex[2], 16)
hex = channelToHex(Math.round(hex / 3));
return hex + hex + hex;
}
// Document
function createImage(tag, width, height){
var image = document.createElement(tag);
if (width) image.width = width;
if (height) image.height = height;
return image;
}
// Canvas
function getContext(canvas){ return canvas.getContext("2d") }
function getData(image, width, height){
return getContext(drawImage(image, width, height)).getImageData(0, 0, width, height);
}
function setData(canvas, data){
getContext(canvas).putImageData(data, 0, 0);
}
function createData(canvas, width, height){
return getContext(canvas).createImageData(width, height);
}
function drawImage(image, width, height){
var canvas = createImage(tagCanvas, width, height);
getContext(canvas).drawImage(image, 0, 0, width, height);
return canvas;
}
}(document);