-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscripts.js
More file actions
1639 lines (1542 loc) · 66.7 KB
/
scripts.js
File metadata and controls
1639 lines (1542 loc) · 66.7 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let colors = [
'#ffffff', // white
'#ff2121', // red
'#ff93c4', // pink
'#ff8135', // orange
'#fff609', // yellow
'#249ca3', // cyan
'#78dc52', // green
'#003fad', // blue
'#87f2ff', // light-blue
'#8e2ec4', // purple
'#a4839f', // Dusty Purple
'#5c406c', // Dark Purple
'#e5cdc4', // Light Beige
'#91463d', // brown
'#000000' // black
];
function findNearestColor(t, s){let e=s[0],h=Math.abs(t[0]-e[0])+Math.abs(t[1]-e[1])+Math.abs(t[2]-e[2]);for(let a=1;a<s.length;a++){var[b,r,M]=s[a],M=Math.abs(t[0]-b)+Math.abs(t[1]-r)+Math.abs(t[2]-M);M<h&&(h=M,e=s[a])}return e}
function getQuantErr(r,t){return r[0]-=t[0],r[1]-=t[1],r[2]-=t[2],r}
function applyErrBitShift(r,t,i,n){i*=multiplier;return r[0]+=t[0]*i>>n,r[1]+=t[1]*i>>n,r[2]+=t[2]*i>>n,r}
function applyErrDiv(r,t,i,n){i*=multiplier,n=1/n;return r[0]+=t[0]*i*n,r[1]+=t[1]*i*n,r[2]+=t[2]*i*n,r}
let enabledColorsList = new Array(colors.length).fill(true);
let filterList = [];
let filterEffectPowerList = [];
let time = 0;
let multiplier = 1;
const listKey = '$I';
const defaultColorList = {
color: colors,
enabledColorsList: new Array(colors.length).fill(true)
};
renderColors();
function updateMultiplier() {
multiplier = parseFloat(document.getElementById('err_multi').value) || 1;
}
// Main function to process the image
/**
* Process the image
*/
function processImage() {
updateMultiplier(); // Update multiplier value
// Retrieve input elements
const fileInput = document.getElementById('fileInput');
const scaleFactorInput = document.getElementById('scaleFactor');
const outputImage = document.getElementById('outputImage');
const colorArr = document.getElementById('colorArr');
const newWidth = document.getElementById('width').value;
const newHeight = document.getElementById('height').value;
const pixelGoal = document.getElementById('maxPixels').value;
const ditheringOption = document.getElementById('ditheringOptions').value;
// Initialize the file reader
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
// Create a canvas to draw the image on
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Adjust canvas size based on settings
setCanvasSize(img, canvas, newWidth, newHeight, pixelGoal, scaleFactorInput.value);
// Draw the image and apply transformations
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
applyFilter(ctx, canvas.width, canvas.height);
applyDithering(ctx, canvas.width, canvas.height, ditheringOption);
// Set the output image source to the processed canvas
outputImage.src = canvas.toDataURL();
};
img.src = e.target.result;
};
reader.readAsDataURL(fileInput.files[0]);
// Add event listener to the download button
const downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', downloadImage);
// Calculate and display the conversion time
}
window.onload = function() {
var colorListsSelect = document.getElementById('colorLists');
colorListsSelect.innerHTML = '';
var defaultOption = document.createElement("option");
defaultOption.text = "Default";
defaultOption.value = listKey + "Default";
colorListsSelect.add(defaultOption);
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.startsWith(listKey)) {
var listName = key.substring(listKey.length);
var option = document.createElement("option");
option.text = listName;
option.value = listName;
colorListsSelect.add(option);
}
}
renderColors();
}
document.getElementById('Filters').addEventListener('change', function() {
var selectedValue = this.value;
var customDiv = document.getElementById('customFilter');
var noiseDiv = document.getElementById('NoiseFilter');
var blurDiv = document.getElementById('blurFilter');
var radiusDiv = document.getElementById('RadiusFilter');
var sliderDiv = document.getElementById('BrightenFilter');
// Hide all divs first
customDiv.style.display = 'none';
noiseDiv.style.display = 'none';
blurDiv.style.display = 'none';
radiusDiv.style.display = 'none';
sliderDiv.style.display = 'none'; // Fixed the typo here
// Show the selected div based on the selected value
if (selectedValue === 'custom') {
customDiv.style.display = 'block';
} else if (selectedValue === 'noise') {
noiseDiv.style.display = 'block';
} else if (selectedValue === 'blur') {
blurDiv.style.display = 'block';
} else if (selectedValue === 'median') {
radiusDiv.style.display = 'block';
} else if (selectedValue === 'Brighten') {
sliderDiv.style.display = 'block';
}
// Store the selected filter option
fliterOption = selectedValue;
});
document.getElementById('sizeSettings').addEventListener('change', function() {
var selectedOption = this.value;
document.getElementById('scaleOptions').style.display = 'none';
document.getElementById('pixelGoalOptions').style.display = 'none';
document.getElementById('widthHeightOptions').style.display = 'none';
document.getElementById(selectedOption + 'Options').style.display = 'block';
});
document.getElementById('red').addEventListener('input', function() {
changeColorPickerColor();
});
document.getElementById('green').addEventListener('input', function() {
changeColorPickerColor();
});
document.getElementById('blue').addEventListener('input', function() {
changeColorPickerColor();
});
document.addEventListener("DOMContentLoaded", function() {
var select = document.getElementById("ditheringOptions");
var hoverBox = document.getElementById("hoverBox");
var hoverDescription = document.getElementById("hoverDescription");
select.addEventListener("mouseover", function(event) {
if (event.target.tagName === "OPTION") {
var optionDescription = event.target.getAttribute("data-description");
var optionRect = event.target.getBoundingClientRect();
hoverDescription.textContent = optionDescription;
hoverBox.style.display = "block";
hoverBox.style.left = optionRect.left + "px";
hoverBox.style.top = (optionRect.top + window.scrollY + 20) + "px"; // Adjusting the position for better visibility
}
});
select.addEventListener("mouseout", function() {
hoverBox.style.display = "none";
});
});
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (!file) return;
const img = new Image();
img.onload = function() {
const widthInput = document.getElementById('width');
const heightInput = document.getElementById('height');
const maxPixelsInput = document.getElementById('maxPixels');
const scaleFactorInput = document.getElementById('scaleFactor');
const screenWidth = window.innerWidth;
const targetWidth = (screenWidth<<2) / 14
const scaleFactor = Math.round((targetWidth / img.width)*10e+2)/10e+2;
const optimizedWidth = Math.floor(img.width * scaleFactor);
const optimizedHeight = Math.floor(img.height * scaleFactor);
widthInput.value = Math.max(optimizedWidth, 1);
heightInput.value = Math.max(optimizedHeight, 1);
scaleFactorInput.value = Math.abs(scaleFactor-1) <= 0.1 ? 1 : scaleFactor;
processImage();
};
const reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
function saveColorList() {
var colorListName = prompt("Enter a name for the color list:");
if (colorListName) {
var savedData = {
color: colors,
enabledColorsList: enabledColorsList
};
localStorage.setItem(listKey + colorListName, JSON.stringify(savedData));
var colorListsSelect = document.getElementById('colorLists');
var option = document.createElement("option");
option.text = colorListName;
option.value = colorListName;
colorListsSelect.add(option);
renderColors();
}
}
function loadColorList() {
var selectedColorListName = document.getElementById('colorLists').value;
if (selectedColorListName != listKey + "Default") {
var fullKey = listKey + selectedColorListName;
var savedData = localStorage.getItem(fullKey);
if (savedData) {
savedData = JSON.parse(savedData);
colors = savedData.color;
enabledColorsList = savedData.enabledColorsList;
}
} else {
colors = defaultColorList.color;
enabledColorsList = defaultColorList.enabledColorsList;
}
renderColors();
}
function removeColorList() {
var selectedColorListName = document.getElementById('colorLists').value;
if (selectedColorListName != listKey + "Default") {
var fullKey = listKey + selectedColorListName;
localStorage.removeItem(fullKey);
var colorListsSelect = document.getElementById('colorLists');
var options = colorListsSelect.options;
for (var i = 0; i < options.length; i++) {
if (options[i].value === selectedColorListName) {
colorListsSelect.remove(i);
break;
}
}
if (colorListsSelect.options.length === 0) {
colors = defaultColorList.color;
enabledColorsList = defaultColorList.enabledColorsList;
renderColors();
}
}
}
/**
* Function to set the canvas size based on user-specified settings.
* This function adjusts the canvas dimensions using one of three methods:
* user-defined width and height, a target pixel goal, or a scale factor.
*
* @param {HTMLImageElement} img - The source image used to determine dimensions.
* @param {HTMLCanvasElement} canvas - The canvas element to resize.
* @param {number} newWidth - Desired width of the canvas. Use -1 to ignore this parameter.
* @param {number} newHeight - Desired height of the canvas. Use -1 to ignore this parameter.
* @param {number} pixelGoal - The target number of pixels for the resized canvas. Ignored unless 'pixelGoal' mode is selected.
* @param {number} scaleFactor - The scaling factor to apply to the image dimensions. Ignored unless 'scaleFactor' mode is selected.
*/
function setCanvasSize(img, canvas, newWidth, newHeight, pixelGoal, scaleFactor) {
const sizeSettings = document.getElementById('sizeSettings').value;
if (sizeSettings === 'widthHeight') {
// Set width and height based on user input or ratio adjustment
if (!(newWidth == -1 && newHeight == -1)) {
canvas.width = newWidth != -1 ? newWidth : img.width * (newHeight / img.height);
canvas.height = newHeight != -1 ? newHeight : img.height * (newWidth / img.width);
} else {
canvas.width = img.width;
canvas.height = img.height;
}
} else if (sizeSettings === 'pixelGoal') {
// Resize based on pixel goal
const newRes = resizePixelGoal(img.width, img.height, pixelGoal);
canvas.width = newRes[0];
canvas.height = newRes[1];
} else {
// Resize based on scale factor
canvas.width = img.width * scaleFactor;
canvas.height = img.height * scaleFactor;
}
}
/**
* Function to apply a specified dithering technique to an image.
* The function processes the image data within a canvas context using the selected dithering algorithm.
*
* @param {CanvasRenderingContext2D} context - The canvas 2D rendering context containing the image data to dither.
* @param {number} w - The width of the image or canvas area to apply the dithering.
* @param {number} h - The height of the image or canvas area to apply the dithering.
* @param {string} ditheringType - The type of dithering to apply. Options include:
* - 'none': No dithering.
* - 'floyd': Floyd-Steinberg dithering.
* - 'nearest': Nearest color dithering.
* - 'bayerMatrix2': Bayer matrix 2x2 dithering.
* - 'bayerMatrix4': Bayer matrix 4x4 dithering.
* - 'bayerMatrix8': Bayer matrix 8x8 dithering.
* - 'bayerMatrix16': Bayer matrix 16x16 dithering.
* - 'falseFloyd': False Floyd-Steinberg dithering.
* - 'stucki': Stucki dithering.
* - 'Burkes': Burkes dithering.
*/
function applyDithering(context, w ,h,ditheringType) {
if (ditheringType == 'none') {
noneDithering(context, w, h)
} else if (ditheringType == 'floyd') {
floydSteinbergDithering(context, w, h);
} else if (ditheringType == 'nearest') {
ClosesColorDithering(context, w, h);
} else if (ditheringType == 'bayerMatrix4') {
bayerDithering4x4(context, w, h)
} else if (ditheringType == 'bayerMatrix8') {
bayerDithering8x8(context, w, h)
} else if (ditheringType == 'falseFloyd') {
FalseFloydSteinbergDithering(context, w, h)
} else if (ditheringType == 'stucki') {
stuckiDithering(context, w, h);
} else if (ditheringType == 'Burkes') {
BurkesDithering(context, w, h);
} else if (ditheringType == 'bayerMatrix2') {
bayerDithering2x2(context, w, h)
} else if (ditheringType == 'bayerMatrix16') {
bayerDithering16x16(context, w, h)
}
}
function applyFilter(context,w,h) {
if (filterList.length > 0) {
for (let i = 0; i < filterList.length; i++) {
if (filterList[i] == 'GrayScale') {
grayScale(context,w,h);
} else if (filterList[i] == 'custom') {
const r = filterEffectPowerList[i][0];
const g = filterEffectPowerList[i][1];
const b = filterEffectPowerList[i][2];
customFilter(context,w,h,r,g,b);
} else if (filterList[i] == 'noise') {
const noiseLevel = filterEffectPowerList[i][0];
noiseFilter(context,w,h,noiseLevel);
} else if (filterList[i] == 'blur') {
const blurPower = Math.min(Math.abs(filterEffectPowerList[i][0]),50);
blurImage(context,w,h, blurPower);
} else if (filterList[i] == 'invert') {
InvertFilter(context,w,h);
} else if (filterList[i] == 'unBlur') {
unblurImage(context,w,h);
} else if (filterList[i] == 'median') {
const radius = Math.min(Math.abs(filterEffectPowerList[i][0]),15);
medianFilter(context,w,h, 1);
} else if (filterList[i] == 'Brighten') {
const brightenStrength = Math.max(Math.abs(filterEffectPowerList[i][0]),0.10)
brightenFilter(context,w,h,)
}
}
} else {
filterType = document.getElementById('Filters').value;
if (filterType == 'GrayScale') {
grayScale(context,w,h);
} else if (filterType == 'custom') {
const r = document.getElementById('red').value;
const g = document.getElementById('green').value;
const b = document.getElementById('blue').value;
customFilter(context,w,h,r,g,b);
} else if (filterType == 'noise') {
const noiseLevel = document.getElementById('noiseLevel').value;
noiseFilter(context,w,h,noiseLevel);
} else if (filterType == 'blur') {
const blurPower = Math.min(Math.abs(document.getElementById('blurPower').value),50);
blurImage(context,w,h, blurPower);
} else if (filterType == 'invert') {
InvertFilter(context,w,h) ;
} else if (filterType == 'unBlur') {
unblurImage(context,w,h);
} else if (filterType == 'median') {
const radius = Math.min(Math.abs(document.getElementById('radius').value),15);
medianFilter(context,w,h, radius);
} else if (filterType == 'Brighten') {
const brightenStrength = Math.max(Math.abs(document.getElementById('Slider')),0.10)
brightenFilter(context,w,h,brightenStrength)
}
}
}
function brightenFilter(context, width, height, brightnessFactor) {
// Get the image data from the canvas
const imageData = context.getImageData(0, 0, width, height);
const data = imageData.data;
// Loop through all the pixels
for (let i = 0; i < data.length; i += 4) {
// Get the RGB values
let r = data[i]; // Red
let g = data[i + 1]; // Green
let b = data[i + 2]; // Blue
// Apply the brightness factor to the perceived brightness
// Increase the brightness proportionally, but don't exceed the max value (255)
r = Math.min(255, r * brightnessFactor);
g = Math.min(255, g * brightnessFactor);
b = Math.min(255, b * brightnessFactor);
// Set the new values to the image data
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
}
// Put the modified image data back to the canvas
context.putImageData(imageData, 0, 0);
}
function medianFilter(context, w, h, radius) {
const imgData = context.getImageData(0, 0, w, h);
const data = imgData.data;
const newData = new Uint8ClampedArray(data.length); // Create a new array to store modified data
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const index = (y * w + x) * 4;
const redValues = [];
const greenValues = [];
const blueValues = [];
for (let j = -radius; j <= radius; j++) {
for (let i = -radius; i <= radius; i++) {
const nx = x + i;
const ny = y + j;
if (nx >= 0 && nx < w && ny >= 0 && ny < h) {
const neighborIndex = (ny * w + nx) * 4;
redValues.push(data[neighborIndex]);
greenValues.push(data[neighborIndex + 1]);
blueValues.push(data[neighborIndex + 2]);
}
}
}
redValues.sort((a, b) => a - b);
greenValues.sort((a, b) => a - b);
blueValues.sort((a, b) => a - b);
const medianRed = redValues[Math.floor(redValues.length / 2)];
const medianGreen = greenValues[Math.floor(greenValues.length / 2)];
const medianBlue = blueValues[Math.floor(blueValues.length / 2)];
newData[index] = medianRed;
newData[index + 1] = medianGreen;
newData[index + 2] = medianBlue;
newData[index + 3] = data[index + 3];
}
}
for (let i = 0; i < data.length; i++) {
data[i] = newData[i];
}
context.putImageData(imgData, 0, 0);
}
const slider = document.getElementById('Slider');
const valueDisplay = document.getElementById('sliderValue');
// Update the percentage display when the slider value changes
slider.addEventListener('input', function() {
const value = (slider.value * 100).toFixed(0); // Multiply by 100 to get percentage
valueDisplay.textContent = '' + value + '%';
});
function downloadImage() {
let varName = document.getElementById('varName').value;
const downloadLink = document.createElement('a');
downloadLink.href = outputImage.src;
downloadLink.download = varName + '.png';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
function convertImgStringToCanvas(imgString) {
imgString = imgString.replace('`', '').replace('img', '');
const rows = imgString.trim().split(/\s{2,}/).map(row => row.trim());
const width = rows[0].split(' ').length;
const height = rows.length;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const inputElement = document.getElementById('scaleFactor');
const scaleFactor = parseFloat(inputElement.value);
const newWidth = document.getElementById('width').value;
const newHeight = document.getElementById('height').value;
const pixelGoal = document.getElementById('maxPixels').value;
if (document.getElementById('sizeSettings').value === 'widthHeight') {
canvas.width = newWidth;
canvas.height = newHeight;
} else if (document.getElementById('sizeSettings').value === 'pixelGoal') {
let newRes = resizePixelGoal(width, height, pixelGoal);
canvas.width = newRes[0];
canvas.height = newRes[1];
} else {
canvas.width = width * scaleFactor;
canvas.height = height * scaleFactor;
}
const wDif = canvas.width / width;
const hDif = canvas.height / height;
for (let y = 0; y < height; y++) {
const rowData = rows[y].split(' ');
for (let x = 0; x < width; x++) {
const data = rowData[x];
if (data !== '.') {
const colorIndex = parseInt(data, 16) - 1;
const color = colors[colorIndex];
ctx.fillStyle = color;
ctx.fillRect(x * wDif, y * hDif, wDif, hDif);
} else {
ctx.fillStyle = '#FFFFFF';
ctx.fillRect(x * wDif, y * hDif, wDif, hDif);
}
}
}
return canvas;
}
function convertAndDownload() {
var makeCodeString = document.getElementById('makeCodeInput').value;
var canvasData = convertImgStringToCanvas(makeCodeString, colors)
var canvas = canvasData;
var ctx = canvas.getContext('2d');
var dataURL = canvas.toDataURL('image/png');
var downloadLink = document.createElement('a');
downloadLink.href = dataURL;
downloadLink.download = document.getElementById('varName').value + '.png';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
function changeColorPickerColor() {
const colorPicker = document.getElementById('colorPicker');
const redInput = parseInt(document.getElementById('red').value);
const greenInput = parseInt(document.getElementById('green').value);
const blueInput = parseInt(document.getElementById('blue').value);
const redHex = ('0' + redInput.toString(16)).slice(-2);
const greenHex = ('0' + greenInput.toString(16)).slice(-2);
const blueHex = ('0' + blueInput.toString(16)).slice(-2);
colorPicker.value = '#' + redHex + greenHex + blueHex;
}
function updateColors() {
const colorPicker = document.getElementById('colorPicker');
const redInput = document.getElementById('red');
const greenInput = document.getElementById('green');
const blueInput = document.getElementById('blue');
const selectedColor = colorPicker.value;
const red = parseInt(selectedColor.substring(1, 3), 16);
const green = parseInt(selectedColor.substring(3, 5), 16);
const blue = parseInt(selectedColor.substring(5, 7), 16);
redInput.value = red;
greenInput.value = green;
blueInput.value = blue;
}
function removedisabledColors(colArr, enabledArr) {
const newPalArr = [];
for (let i = 0; i < colArr.length; i++) {
if (enabledArr[i]) {
newPalArr.push(colArr[i]);
}
}
return newPalArr;
}
function setRGBValues(red, green, blue) {
document.getElementById('red').value = red;
document.getElementById('green').value = green;
document.getElementById('blue').value = blue;
}
function resizePixelGoal(width, height, totalPixelGoal) {
if (totalPixelGoal == -1) {
return [width, height];
}
var currentPixels = width * height;
var aspectRatio = width / height;
var newWidth = Math.sqrt(totalPixelGoal * aspectRatio);
var newHeight = newWidth / aspectRatio;
newWidth = Math.round(newWidth);
newHeight = Math.round(newHeight);
return [newWidth, newHeight];
}
function copyToClipboard() {
let varName = document.getElementById('varName').value;
navigator.clipboard.writeText('let ' + varName + imageString);
alert("Copied successfully! ");
}
function noneDithering(context,w,h) {
palArr = removedisabledColors(hexToRgb(colors),enabledColorsList);
var imgData = context.getImageData(0, 0, w, h);
var data = imgData.data;
var MakecodeImg = []
for (let y = 0; y < h; y++) {
var row = [];
for (let x = 0; x <w; x++) {
const index = (y * w + x) * 4;
const r = data[index];
const g = data[index + 1];
const b = data[index + 2];
row.push(palArr.indexOf(findNearestColor([r,g,b], palArr)) + 1);
}
MakecodeImg.push(row);
}
imageString = ' = img\`\n';
for (let i = 0; i < MakecodeImg.length; i++) {
let rows = MakecodeImg[i];
for (let j = 0; j < rows.length; j++) {
let pixel = rows[j];
imageString += pixel.toString(16) + " ";
}
imageString += "\n";
}
imageString += "`";
}
function bayerDithering2x2(context, width, height) {
const ditherMatrix = [
[0, 2],
[3, 1],
];
const matrixWidth = ditherMatrix[0].length;
const matrixHeight = ditherMatrix.length;
const maxThreshold = Math.max(...ditherMatrix.flat());
const palArr = removedisabledColors(hexToRgb(colors), enabledColorsList);
const imgData = context.getImageData(0, 0, width, height);
const data = imgData.data;
// Normalize the Bayer matrix to 0-1 range
const normalizedMatrix = ditherMatrix.map(row => row.map(value => value / maxThreshold));
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const index = (y * width + x) * 4;
const r = data[index];
const g = data[index + 1];
const b = data[index + 2];
// Normalize pixel intensity
const threshold = normalizedMatrix[y % matrixHeight][x % matrixWidth] - 0.5;
// Add dithering to each channel
const ditheredR = Math.min(Math.max(r / 255 + threshold, 0), 1) * 255;
const ditheredG = Math.min(Math.max(g / 255 + threshold, 0), 1) * 255;
const ditheredB = Math.min(Math.max(b / 255 + threshold, 0), 1) * 255;
// Find the nearest color in the palette
const newColor = findNearestColor([ditheredR, ditheredG, ditheredB], palArr);
// Update the pixel color in the image data
data[index] = newColor[0];
data[index + 1] = newColor[1];
data[index + 2] = newColor[2];
}
}
// Apply the modified image data back to the canvas
context.putImageData(imgData, 0, 0);
}
function bayerDithering4x4(context, width, height) {
const ditherMatrix = [
[ 0, 8, 2, 10],
[12, 4, 14, 6],
[ 3, 11, 1, 9],
[15, 7, 13, 5]
];
const matrixWidth = ditherMatrix[0].length;
const matrixHeight = ditherMatrix.length;
const maxThreshold = Math.max(...ditherMatrix.flat());
const palArr = removedisabledColors(hexToRgb(colors), enabledColorsList);
const imgData = context.getImageData(0, 0, width, height);
const data = imgData.data;
// Normalize the Bayer matrix to 0-1 range
const normalizedMatrix = ditherMatrix.map(row => row.map(value => value / maxThreshold));
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const index = (y * width + x) * 4;
const r = data[index];
const g = data[index + 1];
const b = data[index + 2];
// Normalize pixel intensity
const threshold = normalizedMatrix[y % matrixHeight][x % matrixWidth] - 0.5;
// Add dithering to each channel
const ditheredR = Math.min(Math.max(r / 255 + threshold, 0), 1) * 255;
const ditheredG = Math.min(Math.max(g / 255 + threshold, 0), 1) * 255;
const ditheredB = Math.min(Math.max(b / 255 + threshold, 0), 1) * 255;
// Find the nearest color in the palette
const newColor = findNearestColor([ditheredR, ditheredG, ditheredB], palArr);
// Update the pixel color in the image data
data[index] = newColor[0];
data[index + 1] = newColor[1];
data[index + 2] = newColor[2];
}
}
// Apply the modified image data back to the canvas
context.putImageData(imgData, 0, 0);
}
function bayerDithering8x8(context, width, height) {
const ditherMatrix = [
[0, 48, 12, 60, 3, 51, 15, 63],
[32, 16, 44, 28, 35, 19, 47, 31],
[8, 56, 4, 52, 11, 59, 7, 55],
[40, 24, 36, 20, 43, 27, 39, 23],
[2, 50, 14, 62, 1, 49, 13, 61],
[34, 18, 46, 30, 33, 17, 45, 29],
[10, 58, 6, 54, 9, 57, 5, 53],
[42, 26, 38, 22, 41, 25, 37, 21]
];
const matrixWidth = ditherMatrix[0].length;
const matrixHeight = ditherMatrix.length;
const maxThreshold = Math.max(...ditherMatrix.flat());
const palArr = removedisabledColors(hexToRgb(colors), enabledColorsList);
const imgData = context.getImageData(0, 0, width, height);
const data = imgData.data;
// Normalize the Bayer matrix to 0-1 range
const normalizedMatrix = ditherMatrix.map(row => row.map(value => value / maxThreshold));
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const index = (y * width + x) * 4;
const r = data[index];
const g = data[index + 1];
const b = data[index + 2];
// Normalize pixel intensity
const threshold = normalizedMatrix[y % matrixHeight][x % matrixWidth] - 0.5;
// Add dithering to each channel
const ditheredR = Math.min(Math.max(r / 255 + threshold, 0), 1) * 255;
const ditheredG = Math.min(Math.max(g / 255 + threshold, 0), 1) * 255;
const ditheredB = Math.min(Math.max(b / 255 + threshold, 0), 1) * 255;
// Find the nearest color in the palette
const newColor = findNearestColor([ditheredR, ditheredG, ditheredB], palArr);
// Update the pixel color in the image data
data[index] = newColor[0];
data[index + 1] = newColor[1];
data[index + 2] = newColor[2];
}
}
// Apply the modified image data back to the canvas
context.putImageData(imgData, 0, 0);
}
function bayerDithering16x16(context, width, height) {
const ditherMatrix = [
[ 0, 192, 48, 240, 12, 204, 60, 252, 3, 195, 51, 243, 15, 207, 63, 255],
[128, 64, 176, 112, 140, 76, 188, 124, 131, 67, 179, 115, 143, 79, 191, 127],
[ 32, 224, 16, 208, 44, 236, 28, 220, 35, 227, 19, 211, 47, 239, 31, 223],
[160, 96, 144, 80, 172, 108, 156, 92, 163, 99, 147, 83, 175, 111, 159, 95],
[ 8, 200, 56, 248, 4, 196, 52, 244, 11, 203, 59, 251, 7, 199, 55, 247],
[136, 72, 184, 120, 132, 68, 180, 116, 139, 75, 187, 123, 142, 78, 190, 126],
[ 40, 232, 24, 216, 36, 228, 20, 212, 43, 235, 27, 219, 39, 231, 23, 215],
[168, 104, 152, 88, 164, 100, 148, 84, 171, 107, 155, 91, 167, 103, 151, 87],
[ 2, 194, 50, 242, 14, 206, 62, 254, 1, 193, 49, 241, 13, 205, 61, 253],
[130, 66, 178, 114, 129, 65, 177, 113, 134, 70, 182, 118, 133, 69, 181, 117],
[ 34, 226, 18, 210, 46, 238, 30, 222, 33, 225, 17, 209, 45, 237, 29, 221],
[162, 98, 146, 82, 174, 110, 158, 94, 161, 97, 145, 81, 173, 109, 157, 93],
[ 10, 202, 58, 250, 6, 198, 54, 246, 9, 201, 57, 249, 5, 197, 53, 245],
[138, 74, 186, 122, 137, 73, 185, 121, 140, 76, 188, 124, 141, 77, 189, 125],
[ 42, 234, 26, 218, 38, 230, 22, 214, 41, 233, 25, 217, 37, 229, 21, 213],
[170, 106, 154, 90, 166, 102, 150, 86, 169, 105, 153, 89, 165, 101, 149, 85]
];
const matrixWidth = ditherMatrix[0].length;
const matrixHeight = ditherMatrix.length;
const maxThreshold = Math.max(...ditherMatrix.flat());
const palArr = removedisabledColors(hexToRgb(colors), enabledColorsList);
const imgData = context.getImageData(0, 0, width, height);
const data = imgData.data;
// Normalize the Bayer matrix to 0-1 range
const normalizedMatrix = ditherMatrix.map(row => row.map(value => value / maxThreshold));
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const index = (y * width + x) * 4;
const r = data[index];
const g = data[index + 1];
const b = data[index + 2];
// Normalize pixel intensity
const threshold = normalizedMatrix[y % matrixHeight][x % matrixWidth] - 0.5;
// Add dithering to each channel
const ditheredR = Math.min(Math.max(r / 255 + threshold, 0), 1) * 255;
const ditheredG = Math.min(Math.max(g / 255 + threshold, 0), 1) * 255;
const ditheredB = Math.min(Math.max(b / 255 + threshold, 0), 1) * 255;
// Find the nearest color in the palette
const newColor = findNearestColor([ditheredR, ditheredG, ditheredB], palArr);
// Update the pixel color in the image data
data[index] = newColor[0];
data[index + 1] = newColor[1];
data[index + 2] = newColor[2];
}
}
// Apply the modified image data back to the canvas
context.putImageData(imgData, 0, 0);
}
function ClosesColorDithering(context, w, h) {
var imgData = context.getImageData(0, 0, w, h);
var data = imgData.data;
var MakecodeImg = []
palArr = removedisabledColors(hexToRgb(colors),enabledColorsList);
for (var y = 0; y < h; y++) {
var row = [];
for (var x = 0; x < w; x++) {
var id = ((y * w) + x) * 4;
oldpixel = [data[id], data[id + 1], data[id + 2]];
newpixel = findNearestColor(oldpixel, palArr);
row.push(palArr.indexOf(newpixel) + 1);
data[id] = newpixel[0];
data[id + 1] = newpixel[1];
data[id + 2] = newpixel[2];
data[id + 3] = 255;
}
MakecodeImg.push(row);
}
imageString = ' = img\`\n';
for (let i = 0; i < MakecodeImg.length; i++) {
let rows = MakecodeImg[i];
for (let j = 0; j < rows.length; j++) {
let pixel = rows[j];
imageString += pixel.toString(16) + " ";
}
imageString += "\n";
}
imageString += "`";
context.putImageData(imgData, 0, 0);
}
function floydSteinbergDithering(context, w, h) {
var imgData = context.getImageData(0, 0, w, h);
var data = imgData.data;
var MakecodeImg = []
palArr = removedisabledColors(hexToRgb(colors),enabledColorsList);
for (var y = 0; y < h; y++) {
var row = [];
for (var x = 0; x < w; x++) {
var id = ((y * w) + x) * 4;
oldpixel = [data[id], data[id + 1], data[id + 2]];
newpixel = findNearestColor(oldpixel, palArr);
row.push(palArr.indexOf(newpixel) + 1);
data[id] = newpixel[0];
data[id + 1] = newpixel[1];
data[id + 2] = newpixel[2];
data[id + 3] = 255;
quantErr = getQuantErr(oldpixel, newpixel);
id = ((y * w) + (x + 1)) * 4;
if (id < data.length) {
err = applyErrBitShift([data[id], data[id + 1], data[id + 2]], quantErr, 7,4);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y + 1) * w) + (x - 1)) * 4;
if (id < data.length) {
err = applyErrBitShift([data[id], data[id + 1], data[id + 2]], quantErr, 3,4);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y + 1) * w) + x) * 4;
if (id < data.length) {
err = applyErrBitShift([data[id], data[id + 1], data[id + 2]], quantErr, 5,4);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y + 1) * w) + (x + 1)) * 4;
if (id < data.length) {
err = applyErrBitShift([data[id], data[id + 1], data[id + 2]], quantErr, 1,4);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
}
MakecodeImg.push(row);
}
imageString = ' = img\`\n';
for (let i = 0; i < MakecodeImg.length; i++) {
let rows = MakecodeImg[i];
for (let j = 0; j < rows.length; j++) {
let pixel = rows[j];
imageString += pixel.toString(16) + " ";
}
imageString += "\n";
}
imageString += "`";
context.putImageData(imgData, 0, 0);
}
function FalseFloydSteinbergDithering(context, w, h) {
var imgData = context.getImageData(0, 0, w, h);
var data = imgData.data;
var MakecodeImg = []
palArr = removedisabledColors(hexToRgb(colors),enabledColorsList);
for (var y = 0; y < h; y++) {
var row = [];
for (var x = 0; x < w; x++) {
var id = ((y * w) + x) * 4;
oldpixel = [data[id], data[id + 1], data[id + 2]];
newpixel = findNearestColor(oldpixel, palArr);
row.push(palArr.indexOf(newpixel) + 1);
data[id] = newpixel[0];
data[id + 1] = newpixel[1];
data[id + 2] = newpixel[2];
data[id + 3] = 255;
quantErr = getQuantErr(oldpixel, newpixel);
id = (((y) * w) + (x + 1)) * 4;
if (id < data.length) {
err = applyErrBitShift([data[id], data[id + 1], data[id + 2]], quantErr, 3,3);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y + 1) * w) + (x + 1)) * 4;
if (id < data.length) {
err = applyErrBitShift([data[id], data[id + 1], data[id + 2]], quantErr, 2,3);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y+1) * w) + (x)) * 4;
if (id < data.length) {
err = applyErrBitShift([data[id], data[id + 1], data[id + 2]], quantErr, 3,3);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
}
MakecodeImg.push(row);
}
imageString = ' = img\`\n';
for (let i = 0; i < MakecodeImg.length; i++) {
let rows = MakecodeImg[i];
for (let j = 0; j < rows.length; j++) {
let pixel = rows[j];
imageString += pixel.toString(16) + " ";
}
imageString += "\n";
}
imageString += "`";
context.putImageData(imgData, 0, 0);
}
function stuckiDithering(context, w, h) {
var imgData = context.getImageData(0, 0, w, h);
var data = imgData.data;
var MakecodeImg = []
palArr = removedisabledColors(hexToRgb(colors),enabledColorsList);
for (var y = 0; y < h; y++) {
var row = [];
for (var x = 0; x < w; x++) {
var id = ((y * w) + x) * 4;
oldpixel = [data[id], data[id + 1], data[id + 2]];
newpixel = findNearestColor(oldpixel, palArr);
row.push(palArr.indexOf(newpixel) + 1);
data[id] = newpixel[0];
data[id + 1] = newpixel[1];
data[id + 2] = newpixel[2];
data[id + 3] = 255;
quantErr = getQuantErr(oldpixel, newpixel);
id = (((y) * w) + (x + 1)) * 4;
if (id < data.length) {
err = applyErrDiv([data[id], data[id + 1], data[id + 2]], quantErr, 8,42);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y) * w) + (x + 2)) * 4;
if (id < data.length) {
err = applyErrDiv([data[id], data[id + 1], data[id + 2]], quantErr, 4,42);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y+1) * w) + (x - 2)) * 4;
if (id < data.length) {
err = applyErrDiv([data[id], data[id + 1], data[id + 2]], quantErr, 2,42);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y+1) * w) + (x - 1)) * 4;
if (id < data.length) {
err = applyErrDiv([data[id], data[id + 1], data[id + 2]], quantErr, 4,42);
data[id] = err[0];
data[id + 1] = err[1];
data[id + 2] = err[2];
}
id = (((y+1) * w) + (x)) * 4;
if (id < data.length) {