-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimageMaker.js
More file actions
446 lines (365 loc) · 13.1 KB
/
imageMaker.js
File metadata and controls
446 lines (365 loc) · 13.1 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
const loadImageButton = document.getElementById("loadImageButton")
const imageLink = document.getElementById("imageLink")
const imageLinkInput = document.getElementById("imageLinkInput");
const loadedImage = document.getElementById("loadedImage")
const loadImagePopup = document.querySelector(".loadImagePopup")
const uploadImageButton = document.getElementById("uploadImage")
const imageCanvas = document.getElementById("previewCanvas")
const imageCanvasCtx = imageCanvas.getContext("2d")
imageCanvas.width = 100
imageCanvas.height = 100
const copyCodeButton = document.getElementById("copyCodeButton")
const decoderLinkButton = document.getElementById("decoderLinkButton")
const numworksLinkButton = document.getElementById("numworksLinkButton")
const helpLinkButton = document.getElementById("helpLinkButton")
const connectButton = document.getElementById("connectButton")
const transferButton = document.getElementById("transferButton")
// result fields
const resultStorage = document.getElementById("resultStorage")
const resultWidth = document.getElementById("resultWidth")
const resultHeight = document.getElementById("resultHeight")
// inputting files
const fileInput = document.createElement("input")
fileInput.type = "file"
fileInput.accept = "image/*"
var code = "";
// Setup parameters and listeners
// 1 is not possible
var scale = 2;
// in bits, minimum is 2, max is 8
var colorFoldPower = 5;
var colorFold = 2**colorFoldPower;
const MODE_COLOR = "colors";
const MODE_GRAYSCALE = "grayscale";
const MODE_BLACKWHITE = "blackwhite";
var imageMode = MODE_COLOR;
const resolutionInput = document.getElementById("resolutionInput");
const colorsInput = document.getElementById("colorsInput");
const imageModeInput = document.getElementById("imageMode");
resolutionInput.oninput = () => {
scale = 6 - resolutionInput.value;
if (code.length > 0) {
updateImage();
}
}
colorsInput.oninput = () => {
colorFoldPower = 7-colorsInput.value;
colorFold = 2**colorFoldPower;
if (code.length > 0) {
updateImage();
}
}
imageModeInput.oninput = () => {
imageMode = imageModeInput.value;
if (code.length > 0) {
updateImage();
}
}
resolutionInput.oninput()
colorsInput.oninput()
imageModeInput.oninput()
function openloadImagePopup() {
loadImagePopup.classList.add("openedLoadImagePopup")
uploadImageButton.style.display = "inherit"
imageLink.style.display = "inherit"
imageLinkInput.style.display = "none"
}
function closeloadImagePopup() {
loadImagePopup.classList.remove("openedLoadImagePopup")
}
loadImageButton.onclick = openloadImagePopup
document.addEventListener("click", (event) => {
if (event.target == loadImagePopup) {
// is the background of the popup
closeloadImagePopup()
}
})
uploadImageButton.onclick = function() {
fileInput.click()
}
imageLink.onclick = function() {
uploadImageButton.style.display = "none"
imageLink.style.display = "none"
imageLinkInput.style.display = "block"
}
function animateButton(btn) {
btn.style.animation = "copyButton 1s ease-out"
setTimeout(() => {
btn.style.animation = ""
}, 1100)
}
copyCodeButton.onclick = function() {
navigator.clipboard.writeText(code)
animateButton(copyCodeButton)
}
transferButton.onclick = async function() {
if (fileInput.files.length == 0) {
return;
}
imageName = fileInput.files[0].name;
filename = "";
for (let i = 0 ; i < imageName.length ; i++) {
let l = imageName[i];
if (l == ".") {
break;
} else {
filename += l;
}
}
filename += ".py"
console.log("Transfer : ", filename)
var storage = await calculator.backupStorage();
console.log(storage)
storage.records.push({"name": "test", "type": "py", "autoImport": true/*, position: 0*/, "code": "print('Hello World!')\n"});
console.log(storage)
await calculator.installStorage(storage, function() {
console.log("Transfer réussi")
animateButton(transferButton);
});
}
function setPixel(x, y, color) {
imageCanvasCtx.fillStyle = `rgb(${color[0]},${color[1]},${color[2]})`
imageCanvasCtx.fillRect(x, y, 1, 1)
}
function foldValue(value) {
// return Math.round(value/colorFold)*colorFold
return Math.round(value / colorFold);
}
function unfoldValue(value) {
return value * colorFold;
}
var transparencyColor = [255, 255, 255];
function getRGB(data, width, x, y, isGrayscale, blackWhite) {
var index = (y*width + x)*4;
if (data[index+3] == 0) {
return [foldValue(transparencyColor[0]), foldValue(transparencyColor[1]), foldValue(transparencyColor[2])]
}
let r = data[index];
let g = data[index+1];
let b = data[index+2];
if (isGrayscale) {
let l = foldValue(parseInt(r*.299 + g*.587 + b*.114));
return [l, l, l];
} else if (blackWhite) {
index = (y*width + (x+1))*4;
let r2 = data[index];
let g2 = data[index+1];
let b2 = data[index+2];
index = ((y+1)*width + x)*4;
let r3 = data[index];
let g3 = data[index+1];
let b3 = data[index+2];
if (r + g + b > (r2 + g2 + b2 + r3 + g3 + b3 + 127)/2.3) {
return [foldValue(255), foldValue(255), foldValue(255)]
} else {
return [foldValue(0), foldValue(0), foldValue(0)]
}
} else {
return [foldValue(r), foldValue(g), foldValue(b)];
}
}
function RGBToNumber(color) {
return color[0]*65_025 + color[1]*255 + color[2]
}
// not fully implemented
/*function pixelsToCode(data, width, height) {
result = "data="
for (y=0 ; y<height ; y++) {
result += "("
for (x=0 ; x<width ; x++) {
var color = getRGB(data, width, x, y, isGreyScale)
result += `(${color[0]},${color[1]},${color[2]}),`
}
result += "),"
}
console.log(result.length)
return result
}*/
//const indexesLabels = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,;:!/*-+.-_={}[]()<>@$&%^|\"áâäéêëíîïñśóõöúûüÿ☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼┤ÁÂÀ©╣║↕7╝¢¥┐└┴┬├─┼Ã╚ÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒ"
const indexesLabels = `{zEDGFA@CBMLONIHKJUTWVQPSR]_^YX[Z%̈$'&! #"-,/.̄)(+*=<?>;:
¢¡®¬«©±°§¦¥¤£edgfa\`cbmlonihkjutwvqpsr}\|~yx`
/*# s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,;:!/*-+._={}[]()<>@$&%^|\"☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕¶§▬↨↑↓→←∟↔▲▼┤©╣║╝¢¥┐└┴┬├─┼╚ı┘┌█▄¦▀ß"
s="".join([chr(i) for i in range(256)])
s="""¡¢£¤¥¦§̈©«¬®̄°±%$'&! #"-,/.)(+*54761032=<?>98;:
edgfa`cbmlonihkjutwvqpsr}|~yx{zEDGFA@CBMLONIHKJUTWVQPSR]\_^YX[Z"""*/
function pixelsToCodeIndexed(data, width, height, partitionLength) {
if (indexesLabels.length < partitionLength || partitionLength <= 0) {
throw Exception(`Bad partitionLength value: ${partitionLength}`)
}
let isGrayscale;
if (imageMode == MODE_GRAYSCALE) {
isGrayscale = true;
} else {
isGrayscale = false;
}
let isBlackwhite;
if (imageMode == MODE_BLACKWHITE) {
isBlackwhite = true;
} else {
isBlackwhite = false;
}
const indexed = {} // colorKey : [color, label]
var indexedCount = 0
function colorToKey(col) {
return `${col[0]},${col[1]},${col[2]}`
}
for (y=0 ; y<height ; y++) {
for (x=0 ; x<width ; x++) {
color = getRGB(data, width, x, y, isGrayscale, isBlackwhite)
key = colorToKey(color)
if (!(key in indexed)) {
// console.log(color[0]*colorFold, color[1]*colorFold, color[2]*colorFold)
indexed[key] = [color, indexesLabels[indexedCount]] // TODO: chose most important colors
indexedCount += 1
if (indexedCount >= partitionLength) {
break
}
}
}
if (indexedCount >= partitionLength) {
break
}
}
// console.log(indexed)
console.log(indexedCount)
var pixels = "";
var label = "";
var lastLabel = "";
var repetitionCount = 0;
var color;
for (y=0 ; y<height ; y++) {
for (x=0 ; x<width ; x++) {
color = getRGB(data, width, x, y, isGrayscale, isBlackwhite)
values = indexed[colorToKey(color)]
if (values == undefined) {
[color, label] = Object.values(indexed)[0] // TODO: implement a way to use the more appropriate color
} else {
label = values[1]
}
// emulate drawing
setPixel(x, y, [unfoldValue(color[0]), unfoldValue(color[1]), unfoldValue(color[2])])
if (lastLabel == label) {
repetitionCount += 1
} else {
if (repetitionCount > 1) {
pixels += repetitionCount
}
pixels += lastLabel
lastLabel = label
repetitionCount = 1
}
}
}
var colors = ""
Object.keys(indexed).forEach((key) => {
colors += `${RGBToNumber(indexed[key][0])},`
})
var result = `from imgdraw_opti import *\np=prs(${colorFoldPower},"""${indexesLabels.slice(0, indexedCount)}""",(${colors}))\ndr(p,${width},${height},"""${pixels}""",${scale})`
console.log(result.length)
return result
}
function updateImage() {
const maxWidth = 320/scale
const maxHeight = 220/scale
width = loadedImage.naturalWidth
height = loadedImage.naturalHeight
if (width > maxWidth) {
height *= maxWidth/width
width = maxWidth
}
if (height > maxHeight) {
width *= maxHeight/height
height = maxHeight
}
width = Math.round(width)
height = Math.round(height)
imageCanvas.width = width
imageCanvas.height = height
imageCanvasCtx.imageSmoothingEnabled = false
imageCanvasCtx.drawImage(loadedImage, 0, 0, loadedImage.naturalWidth, loadedImage.naturalHeight, 0, 0, width, height)
var data = imageCanvasCtx.getImageData(0, 0, imageCanvas.width, imageCanvas.height).data
code = pixelsToCodeIndexed(data, imageCanvas.width, imageCanvas.height, indexesLabels.length)
var codeLength = code.length
if (codeLength < 1000) {
resultStorage.innerText = `${codeLength} octets`
} else {
resultStorage.innerText = `${Math.round(codeLength/10)/100} Ko`
if (codeLength > 12000) {
resultStorage.innerText += " ⚠"
}
}
resultStorage.classList.remove("resultStorageSmall")
resultStorage.classList.remove("resultStorageMedium")
resultStorage.classList.remove("resultStorageBig")
if (codeLength < 4000) {
resultStorage.classList.add("resultStorageSmall")
} else if (codeLength < 8000) {
resultStorage.classList.add("resultStorageMedium")
} else {
resultStorage.classList.add("resultStorageBig")
}
resultWidth.innerText = width
resultHeight.innerText = height
}
fileInput.onchange = function(e) {
var reader = new FileReader()
reader.readAsDataURL(e.target.files[0])
console.log(e.target.files[0])
reader.onload = readerEvent => {
var content = readerEvent.target.result
loadedImage.src = content
loadedImage.onload = function() {
updateImage();
}
}
closeloadImagePopup()
}
imageLinkInput.addEventListener("keydown", (event) => {
if (event.key == "Enter") {
loadedImage.src = imageLinkInput.value
loadedImage.onload = function() {
updateImage();
}
loadedImage.onerror = function() {
console.log("Image failed to load...")
}
closeloadImagePopup()
}
})
// Connexion to the calculator
var calculator = new Numworks();
function onCalculatorConnected() {
console.log("Numworks Connected");
transferButton.disabled = false;
connectButton.disabled = true;
}
function setupCalculator() {
transferButton.disabled = true;
connectButton.disabled = false;
navigator.usb.addEventListener("disconnect", function(e) {
calculator.onUnexpectedDisconnect(e, function() {
console.log("Numworks Disconnected");
transferButton.disabled = true;
connectButton.disabled = false;
});
});
}
// TODO : NOT SUPPORTED YET
if (/*navigator.usb*/ false) {
setupCalculator();
// Show the buttons
connectButton.hidden = false;
transferButton.hidden = false;
connectButton.addEventListener("click", () => {
console.log("Numworks detection");
animateButton(connectButton)
calculator.detect(onCalculatorConnected, function(error) {
console.log(error);
});
})
} else {
copyCodeButton.hidden = false;
decoderLinkButton.hidden = false;
numworksLinkButton.hidden = false;
helpLinkButton.hidden = false;
}