File size: 95,364 Bytes
85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a 3f92098 85b977a | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pocket Image Editor</title>
<style>
:root{
--bg:#0e1116; --panel:#161b22; --panel2:#1c232d; --line:#2a323d;
--txt:#e6edf3; --dim:#8b98a5; --accent:#4cc2ff; --accent2:#2a9fd6;
--ok:#3fb950; --warn:#d29922; --danger:#f85149; --red:#7f1018;
--r:10px;
}
*{box-sizing:border-box}
html,body{margin:0;min-height:100%}
body{
background:var(--bg); color:var(--txt);
font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
-webkit-font-smoothing:antialiased;
}
.wrap{max-width:1180px;margin:0 auto;padding:20px 20px 60px}
header{display:flex;align-items:center;gap:12px;margin-bottom:14px}
header h1{font-size:17px;margin:0;font-weight:600;letter-spacing:.2px}
header .sub{color:var(--dim);font-size:12.5px}
header .verwrap{display:flex;flex-direction:column;align-items:center;gap:3px}
header .ver{color:var(--dim);font-size:12px;font-variant-numeric:tabular-nums;
border:1px solid var(--line);border-radius:99px;padding:3px 10px;background:var(--panel)}
header .by{color:var(--dim);font-size:10px;letter-spacing:.3px;opacity:.8}
.profileLink{text-decoration:none;color:inherit;border-radius:10px;padding:2px 3px;transition:.12s}
.profileLink:hover{background:var(--panel2)}
.profileLink:hover .ver{border-color:var(--accent);color:var(--accent)}
.profileLink:hover .by{color:var(--txt);opacity:1}
.spacer{flex:1}
button{
font:inherit;color:var(--txt);background:var(--panel2);border:1px solid var(--line);
padding:7px 13px;border-radius:8px;cursor:pointer;transition:.12s;
}
button:hover:not(:disabled){background:#242d39;border-color:#3a4553}
button:disabled{opacity:.4;cursor:not-allowed}
button:focus-visible,input:focus-visible,select:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
button.primary{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
button.primary:hover:not(:disabled){background:#6bcfff}
button.ghost{background:transparent}
button.danger{color:#ffb4ae;border-color:#5a2b2b}
button.danger:hover:not(:disabled){background:#341c1c;border-color:#7a3a3a}
.small{padding:5px 10px;font-size:12.5px}
/* ---------- drop zone ---------- */
#drop{
border:2px dashed var(--line);border-radius:14px;padding:40px 24px;text-align:center;background:var(--panel);
cursor:pointer;transition:.15s;margin-bottom:16px;
}
#drop:hover,#drop.over{border-color:var(--accent);background:#12212b}
#drop .big{font-size:38px;line-height:1;margin-bottom:12px;opacity:.65}
#drop h2{margin:0 0 6px;font-size:17px;font-weight:600}
#drop p{margin:0;color:var(--dim);font-size:12.5px}
#drop .row2{display:flex;gap:8px;justify-content:center;margin-top:14px;flex-wrap:wrap}
#drop{position:relative}
#dropToggle{position:absolute;top:8px;right:8px;padding:3px 10px;font-size:12px;border-radius:7px;z-index:2}
#dropToggle .chev{display:inline-block;transition:transform .15s;font-size:10px}
/* collapsed state */
#drop.mini{padding:10px 14px;text-align:left;border-style:solid;display:flex;align-items:center;gap:10px}
#drop.mini .big,#drop.mini h2,#drop.mini p{display:none}
#drop.mini .row2{margin:0;justify-content:flex-start}
#drop.mini #dropToggle{position:static;margin-left:auto}
#drop .miniLabel{display:none;font-size:12.5px;color:var(--dim)}
#drop.mini .miniLabel{display:block}
#drop.mini .miniLabel b{color:var(--txt);font-weight:600}
/* ---------- page-wide drop overlay ---------- */
#pageDrop{position:fixed;inset:0;z-index:9999;display:none;align-items:center;justify-content:center;
background:rgba(8,14,20,.82);backdrop-filter:blur(3px);pointer-events:none}
#pageDrop.show{display:flex}
#pageDrop .box{border:3px dashed var(--accent);border-radius:20px;padding:44px 60px;text-align:center;
background:rgba(18,33,43,.92);box-shadow:0 20px 60px rgba(0,0,0,.5)}
#pageDrop .box .big{font-size:46px;opacity:.8;margin-bottom:10px}
#pageDrop .box h2{margin:0 0 6px;font-size:20px}
#pageDrop .box p{margin:0;color:var(--dim);font-size:13px}
/* ---------- layout ---------- */
.grid{display:grid;grid-template-columns:1fr 330px;gap:18px;align-items:start}
@media(max-width:940px){.grid{grid-template-columns:1fr}}
.card{background:#11161d;border:1px solid var(--line);border-radius:var(--r);padding:14px}
.card h3,.panelbox h3{margin:0 0 12px;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim);font-weight:600}
.panelbox{background:#0d1219;border:1px solid var(--line);border-radius:10px;padding:10px 12px 12px;margin-bottom:14px}
.panelbox:last-child{margin-bottom:0}
h3.collap{display:flex;align-items:center;justify-content:space-between;cursor:pointer;user-select:none;
margin:-10px -12px 10px;padding:9px 12px;border-radius:9px 9px 0 0;background:#171d26;
border-bottom:1px solid var(--line);color:var(--txt)}
h3.collap:hover{background:#1c232d}
h3.collap.shut{margin-bottom:-12px;border-bottom:none;border-radius:9px}
h3.collap .chev{font-size:11px;color:var(--accent);transition:transform .15s}
h3.collap.shut .chev{transform:rotate(-90deg)}
.collapbody.shut{display:none}
/* ---------- view tabs ---------- */
.viewtabs{display:flex;gap:5px;margin-bottom:12px}
.viewtabs button{padding:6px 14px;font-size:12.5px;border-radius:8px}
.viewtabs button.on{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
/* ---------- queue ---------- */
.q-head{display:flex;align-items:center;gap:8px;margin:0 0 8px;flex-wrap:wrap}
.q-head h3{margin:0;font-size:12px;text-transform:uppercase;letter-spacing:.7px;color:var(--dim);font-weight:600}
.qlist{border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel);max-height:420px;overflow-y:auto}
.qrow{display:flex;align-items:center;gap:10px;padding:7px 10px;border-top:1px solid var(--line);font-size:12.5px}
.qrow:first-child{border-top:none}
.qrow:hover{background:var(--panel2)}
.qrow.on{background:#12212b;box-shadow:inset 2px 0 0 var(--accent)}
.qrow input[type=checkbox]{width:16px;height:16px;flex:none;accent-color:var(--accent);cursor:pointer}
.qthumb{width:52px;height:40px;border-radius:4px;border:1px solid var(--line);background:#07090c;flex:none;object-fit:cover;display:block}
.qthumb.ph{display:flex;align-items:center;justify-content:center;color:var(--dim);font-size:16px}
.qmeta{flex:1 1 90px;min-width:60px;overflow:hidden}
.qname{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.qsub{color:var(--dim);font-size:11px;font-variant-numeric:tabular-nums;margin-top:1px}
.qstate{font-size:11px;font-variant-numeric:tabular-nums;flex:none;width:74px;text-align:right}
.qstate.done{color:var(--ok)} .qstate.err{color:#ffb4ae} .qstate.work{color:var(--accent)}
.qx{padding:2px 8px;font-size:13px;border-radius:6px;flex:none}
.empty{color:var(--dim);font-size:12.5px;text-align:center;padding:24px 10px}
/* ---------- grid view ---------- */
.imgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(122px,1fr));gap:10px}
.gcard{position:relative;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel);cursor:pointer;transition:.12s}
.gcard:hover{border-color:#3a4553}
.gcard.on{box-shadow:0 0 0 2px var(--accent);border-color:var(--accent)}
.gcard img{width:100%;height:104px;object-fit:cover;display:block;background:#07090c}
.gcard .gph{width:100%;height:104px;display:flex;align-items:center;justify-content:center;color:var(--dim);font-size:20px;background:#07090c}
.gcard .gname{font-size:11px;padding:5px 7px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--txt)}
.gcard .gchk{position:absolute;top:6px;left:6px;width:18px;height:18px;accent-color:var(--accent);cursor:pointer;z-index:2}
.gcard .gx{position:absolute;top:4px;right:4px;padding:1px 7px;font-size:12px;line-height:1.5;border-radius:6px;
background:rgba(0,0,0,.55);color:var(--dim);z-index:2}
.gcard .gx:hover{color:#ffb4ae;border-color:#5a2b2b;background:#341c1c}
.gcard .gstate{position:absolute;bottom:24px;right:5px;font-size:10px;padding:1px 6px;border-radius:5px;background:rgba(0,0,0,.6);font-variant-numeric:tabular-nums}
.gcard .gstate.done{color:#9ae6a8} .gcard .gstate.err{color:#ffb4ae} .gcard .gstate.work{color:var(--accent)}
/* ---------- preview stage ---------- */
.stage{background:#000;border-radius:var(--r);overflow:hidden;display:flex;align-items:center;justify-content:center;
position:relative;border:1px solid var(--line);min-height:240px;margin-bottom:14px}
.stage canvas{max-width:100%; touch-action:none; user-select:none; cursor:default;max-height:52vh;width:auto;height:auto;display:block;background:#000}
.badge{position:absolute;top:10px;left:10px;z-index:3;background:rgba(0,0,0,.66);backdrop-filter:blur(4px);
padding:4px 9px;border-radius:6px;font-size:11.5px;color:#cfe;letter-spacing:.3px}
.ba-right{left:auto;right:10px;color:#bfe9ff}
/* ---------- settings ---------- */
.row{display:flex;align-items:center;gap:8px;margin-bottom:10px}
.row label{flex:0 0 92px;color:var(--dim);font-size:12.5px}
.row:last-child{margin-bottom:0}
input[type=text],input[type=number],textarea,select{
font:inherit;background:var(--panel2);color:var(--txt);border:1px solid var(--line);
border-radius:7px;padding:6px 8px;width:100%;min-width:0;
}
input[type=color]{padding:2px;height:31px;width:44px;flex:none;background:var(--panel2);
border:1px solid var(--line);border-radius:7px;cursor:pointer}
input:focus,textarea:focus,select:focus{outline:none;border-color:var(--accent)}
input[type=range]{width:100%;accent-color:var(--accent)}
.seg{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:10px}
.seg button{padding:5px 9px;font-size:12.5px;border-radius:7px;flex:1 1 auto}
.seg button.on{background:var(--accent);border-color:var(--accent);color:#04121c;font-weight:600}
.hint{color:var(--dim);font-size:11.5px;margin:-2px 0 10px;line-height:1.45}
.chk{display:flex;align-items:center;gap:7px;color:var(--txt);font-size:12.5px;margin-bottom:10px;cursor:pointer}
.chk input{width:auto;flex:none;accent-color:var(--accent)}
.chk .sub{color:var(--dim);font-size:11px}
.est{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:9px 11px;font-size:12.5px;margin-bottom:12px}
.est div{display:flex;justify-content:space-between;margin:2px 0;gap:10px}
.est span{color:var(--dim)}
.est b{font-variant-numeric:tabular-nums;font-weight:600;text-align:right}
.expBtn{width:100%;padding:11px}
.stopBtn{width:100%;padding:9px;margin-top:8px;display:none}
.bar{height:6px;background:var(--panel2);border-radius:99px;overflow:hidden;margin-top:10px;display:none}
.bar i{display:block;height:100%;width:0;background:var(--accent);transition:width .2s}
.status{font-size:12px;color:var(--dim);margin-top:8px;text-align:center;min-height:16px;line-height:1.4}
.status.err{color:#ffb4ae}
.status.ok{color:#9ae6a8}
.note{font-size:11.5px;color:var(--warn);margin-top:8px;line-height:1.4}
.toolbtns{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:6px}
.toolbtns button{flex:1 1 auto;padding:6px 8px;font-size:12.5px}
.keys{color:var(--dim);font-size:11.5px;margin-top:12px;line-height:1.7}
.kbd{display:inline-block;background:var(--panel2);border:1px solid var(--line);border-bottom-width:2px;
border-radius:5px;padding:0 5px;font-size:11px;font-family:ui-monospace,Menlo,Consolas,monospace}
code{background:var(--panel2);border:1px solid var(--line);border-radius:4px;padding:0 4px;font-size:11.5px}
@media(prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important}}
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>Pocket Image Editor</h1>
<span class="sub">convert · resize · GIF timing · captions & memes</span>
<span class="spacer"></span>
<a class="verwrap profileLink" href="https://huggingface.co/PoopMan333" target="_blank" rel="noopener noreferrer" title="Open PoopMan333 on Hugging Face"><span class="ver">v3.0</span><span class="by">by C_Nugget</span></a>
</header>
<div id="drop" aria-label="Add images">
<button id="dropToggle" class="ghost" type="button" title="Collapse / expand" aria-expanded="true">Hide <span class="chev">▲</span></button>
<span class="miniLabel"><b>Add more images</b> · or drop them anywhere on the page</span>
<div class="big">▢</div>
<h2>Drop images here to convert</h2>
<p>HEIC / HEIF · JPEG / JFIF · PNG · WebP · AVIF · GIF · BMP · TIFF* · ICO · add as many as you like · nothing is uploaded, it all stays on this computer</p>
<div class="row2">
<button id="pickFiles" class="small">Choose files</button>
<button id="pickFolder" class="small ghost">Choose a folder</button>
</div>
<input type="file" id="fileInput" accept="image/*,.heic,.heif,.heics,.jfif,.pjpeg,.pjp,.avif,.tif,.tiff,.bmp,.ico" multiple hidden>
<input type="file" id="folderInput" webkitdirectory directory multiple hidden>
</div>
<div class="grid">
<!-- LEFT: preview + queue -->
<div>
<div class="viewtabs" id="viewTabs">
<button data-v="preview" class="on">Preview</button>
<button data-v="grid">Grid</button>
</div>
<div id="previewView">
<div class="stage">
<canvas id="preview"></canvas>
<div class="badge" id="srcBadge">No image selected</div>
<div class="badge ba-right" id="outBadge"></div>
</div>
</div>
<div id="gridView" style="display:none">
<div class="imgrid" id="imgrid"></div>
</div>
<div class="q-head">
<h3>Queue</h3>
<span class="hint" id="qCount" style="margin:0">0 images</span>
<span class="spacer"></span>
<button class="small ghost" id="selAll">Select all</button>
<button class="small ghost" id="selNone">None</button>
<button class="small ghost" id="clearDone">Clear finished</button>
<button class="small ghost" id="clearAll">Remove all</button>
</div>
<div id="listView">
<div class="qlist" id="qList"><div class="empty">No images yet. Drop files above and they will appear here in order.</div></div>
</div>
<div class="keys">
<span class="kbd">←</span> <span class="kbd">→</span> move between images ·
<span class="kbd">Space</span> toggle selected ·
<span class="kbd">R</span> rotate · <span class="kbd">Del</span> remove ·
<span class="kbd">Ctrl</span>+<span class="kbd">V</span> paste an image ·
only <b style="color:var(--txt)">ticked</b> images are converted; edits apply to every image.
</div>
</div>
<!-- RIGHT: settings -->
<div class="card">
<!-- Output format -->
<div class="panelbox">
<h3>Output format</h3>
<div class="seg" id="fmtSeg">
<button data-fmt="image/png" class="on">PNG</button>
<button data-fmt="image/jpeg">JPEG</button>
<button data-fmt="image/webp">WebP</button>
<button data-fmt="image/avif">AVIF</button>
<button data-fmt="image/gif">GIF</button>
<button data-fmt="application/pdf">PDF</button>
</div>
<div class="row" id="qualityRow">
<label>Quality</label>
<input type="range" id="quality" min="1" max="100" value="82">
<b class="hint" id="qualityL" style="margin:0;flex:0 0 36px;text-align:right;color:var(--txt)">82</b>
</div>
<label class="chk" id="targetChk"><input type="checkbox" id="targetOn"> Target file size <span class="sub">(auto-tunes quality)</span></label>
<div class="row" id="targetRow" style="display:none">
<label>Max size</label>
<input type="number" id="targetSize" min="0.05" step="0.1" value="2" style="flex:1">
<select id="targetUnit" style="flex:0 0 78px"><option value="1048576" selected>MB</option><option value="1024">KB</option></select>
</div>
<!-- PNG mode -->
<div id="pngOpts" style="display:none">
<div class="row">
<label>PNG mode</label>
<select id="pngColors">
<option value="0" selected>Lossless · best quality (24-bit)</option>
<option value="256">Indexed · 256 colours</option>
<option value="128">Indexed · 128 colours</option>
<option value="64">Indexed · 64 colours</option>
<option value="32">Indexed · 32 colours</option>
</select>
</div>
<label class="chk" id="ditherChk" style="display:none"><input type="checkbox" id="pngDither" checked> Dither <span class="sub">(smoother gradients)</span></label>
</div>
<div class="hint" id="fmtHint">PNG is lossless — great for screenshots and graphics. The quality slider only affects JPEG, WebP and AVIF.</div>
</div>
<!-- Resize -->
<div class="panelbox">
<h3 class="collap shut" data-target="resizeBody">Resize <span class="chev">▼</span></h3>
<div class="collapbody shut" id="resizeBody">
<div class="seg" id="resizeMode">
<button data-m="none" class="on">Original</button>
<button data-m="pct">Percent</button>
<button data-m="px">Pixels</button>
<button data-m="max">Max side</button>
</div>
<div class="row" id="pctRow" style="display:none"><label>Scale</label><input type="number" id="pct" min="1" max="400" step="1" value="100"><span class="hint" style="margin:0">%</span></div>
<div id="pxRows" style="display:none">
<div class="row"><label>Width</label><input type="number" id="pxW" min="1" step="1"></div>
<div class="row"><label>Height</label><input type="number" id="pxH" min="1" step="1"></div>
<label class="chk"><input type="checkbox" id="lockAr" checked> Lock aspect ratio</label>
</div>
<div class="row" id="maxRow" style="display:none">
<label>Longest side</label>
<select id="maxPreset">
<option value="640">640 px</option>
<option value="1024">1024 px</option>
<option value="1600" selected>1600 px</option>
<option value="1920">1920 px</option>
<option value="2560">2560 px</option>
<option value="4096">4096 px</option>
</select>
</div>
<div class="hint">Images are only ever scaled down to fit — never blown up past their real pixels unless you use Percent above 100.</div>
</div>
</div>
<!-- Adjust -->
<div class="panelbox">
<h3 class="collap shut" data-target="adjBody">Rotate & flip <span class="chev">▼</span></h3>
<div class="collapbody shut" id="adjBody">
<div class="toolbtns">
<button id="rotL" title="Rotate left">↶ Left</button>
<button id="rotR" title="Rotate right (R)">Right ↷</button>
</div>
<div class="toolbtns">
<button id="flipH">⇆ Flip H</button>
<button id="flipV">⇅ Flip V</button>
<button id="resetAdj" class="ghost">Reset</button>
</div>
<label class="chk"><input type="checkbox" id="autoExif" checked> Auto-rotate from EXIF <span class="sub">(fixes sideways iPhone photos)</span></label>
<div class="hint">Rotate / flip applies to every image in the queue.</div>
</div>
</div>
<div class="panelbox">
<h3 class="collap shut" data-target="cropBody">Crop & straighten <span class="chev">▼</span></h3>
<div class="collapbody shut" id="cropBody">
<div class="row"><label>Preset</label><select id="cropPreset"><option value="free">Free crop</option><option value="1:1">Square 1:1</option><option value="4:3">4:3</option><option value="3:2">3:2</option><option value="16:9">16:9</option><option value="9:16">Story 9:16</option></select></div>
<div class="row"><label>Left</label><input type="range" id="cropL" min="0" max="45" value="0"><b class="hint" id="cropLL" style="margin:0;flex:0 0 34px">0%</b></div>
<div class="row"><label>Right</label><input type="range" id="cropR" min="0" max="45" value="0"><b class="hint" id="cropRL" style="margin:0;flex:0 0 34px">0%</b></div>
<div class="row"><label>Top</label><input type="range" id="cropT" min="0" max="45" value="0"><b class="hint" id="cropTL" style="margin:0;flex:0 0 34px">0%</b></div>
<div class="row"><label>Bottom</label><input type="range" id="cropB" min="0" max="45" value="0"><b class="hint" id="cropBL" style="margin:0;flex:0 0 34px">0%</b></div>
<div class="row"><label>Straighten</label><input type="range" id="straighten" min="-15" max="15" step="0.1" value="0"><b class="hint" id="straightenL" style="margin:0;flex:0 0 42px">0°</b></div>
<button id="resetCrop" type="button" class="ghost" style="width:100%">Reset crop</button>
<div class="hint">Crop is non-destructive and applies to preview and export. Straightening trims the rotated edges.</div>
</div>
</div>
<!-- Text and meme editor -->
<div class="panelbox">
<h3 class="collap shut" data-target="wmBody">Text & meme <span class="chev">▼</span></h3>
<div class="collapbody shut" id="wmBody">
<div class="row" style="align-items:flex-start"><label>Text layers</label><div style="flex:1"><select id="textLayerList" size="3" style="margin-bottom:6px"></select><div class="toolbtns" style="margin:0"><button id="addTextLayer" type="button">+ Add</button><button id="dupTextLayer" type="button">Duplicate</button><button id="delTextLayer" type="button" class="danger">Delete</button></div></div></div>
<div class="row"><label>Style</label><select id="textMode"><option value="none">None</option><option value="bubble">WhatsApp-style bubble</option><option value="meme">Meme text</option><option value="topbox">Black box above</option><option value="bottombox">Black box below</option></select></div>
<div class="row"><label>Text</label><textarea id="wmText" rows="3" placeholder="Type text or emoji 😀"></textarea></div>
<div class="hint" style="margin:-4px 0 10px 100px">Emoji work in the text box — copy one from anywhere and paste it in. Whether it draws depends on the emoji your operating system has; very new ones may come out as an empty box.</div>
<div class="row"><label>Position</label><select id="wmPos"><option value="tl">Top left</option><option value="tc">Top centre</option><option value="tr">Top right</option><option value="c">Centre</option><option value="bl">Bottom left</option><option value="bc" selected>Bottom centre</option><option value="br">Bottom right</option></select></div>
<div class="row"><label>Font</label><select id="wmFont"><option value="Impact,Arial Black,sans-serif">Impact / meme</option><option value="Arial,Segoe UI,sans-serif" selected>Arial</option><option value="Georgia,serif">Georgia</option><option value="Comic Sans MS,cursive">Comic Sans</option><option value="system-ui,sans-serif">System / emoji</option></select></div>
<div class="row"><label>Size</label><input type="range" id="wmSize" min="2" max="30" step="0.1" value="7"><b class="hint" id="wmSizeL" style="margin:0;flex:0 0 36px;text-align:right;color:var(--txt)">7%</b></div>
<div class="row"><label>Text colour</label><input type="color" id="wmColor" value="#ffffff"><span class="spacer"></span><label style="flex:0 0 auto">Background</label><input type="color" id="wmBg" value="#000000"></div>
<div class="hint" id="dragHint">For WhatsApp bubbles, drag the text directly on the preview. Drag the round handle to rotate. Drag the square corner to increase or decrease the text and box size together. Editing handles appear only in the preview, never in saved files.</div>
<div class="row"><label>Padding</label><input type="range" id="wmPad" min="0" max="100" value="45"><b class="hint" id="wmPadL" style="margin:0;flex:0 0 36px;text-align:right;color:var(--txt)">45%</b></div>
<div class="row"><label>Opacity</label><input type="range" id="wmOpacity" min="10" max="100" value="95"><b class="hint" id="wmOpacityL" style="margin:0;flex:0 0 36px;text-align:right;color:var(--txt)">95%</b></div>
<label class="chk"><input type="checkbox" id="wmStroke" checked> Outline text <span class="sub">(recommended for memes)</span></label>
</div>
</div>
<div class="panelbox">
<h3 class="collap shut" data-target="gifBody">Animated GIF <span class="chev">▼</span></h3>
<div class="collapbody shut" id="gifBody">
<div class="row"><label>Playback speed</label><input type="range" id="gifSpeed" min="25" max="400" value="100"><b class="hint" id="gifSpeedL" style="margin:0;flex:0 0 46px;text-align:right;color:var(--txt)">100%</b></div>
<label class="chk"><input type="checkbox" id="gifLoop" checked> Loop animation</label>
<label class="chk"><input type="checkbox" id="gifTransparent" checked> Preserve transparent pixels</label>
<div class="row"><label>Alpha cutoff</label><input type="range" id="gifAlpha" min="1" max="254" value="128"><b class="hint" id="gifAlphaL" style="margin:0;flex:0 0 38px">128</b></div>
<div class="hint">Animated GIFs use all decoded frames when the browser supports ImageDecoder. If it does not, the first frame is still editable.</div>
</div>
</div>
<!-- Naming -->
<div class="panelbox">
<h3 class="collap shut" data-target="nameBody">File names <span class="chev">▼</span></h3>
<div class="collapbody shut" id="nameBody">
<div class="seg" id="nameMode">
<button data-m="keep" class="on">Keep original</button>
<button data-m="tpl">Template</button>
</div>
<div id="tplRows" style="display:none">
<div class="row"><label>Prefix</label><input type="text" id="prefix" placeholder="e.g. web_"></div>
<div class="row"><label>Base</label><input type="text" id="tpl" value="IMG_{n}"></div>
<div class="row"><label>Suffix</label><input type="text" id="suffix" placeholder="e.g. _v2"></div>
<div class="hint">Tokens: <code>{n}</code> number · <code>{name}</code> original name · <code>{date}</code> today · <code>{w}</code>/<code>{h}</code> output size.</div>
</div>
<div class="row"><label>Start #</label><input type="number" id="startN" min="0" step="1" value="1"></div>
</div>
</div>
<!-- Export -->
<div class="panelbox">
<h3>Export</h3>
<div class="est">
<div><span>Selected</span><b id="eCount">—</b></div>
<div><span>Output format</span><b id="eFmt">PNG</b></div>
<div><span>Selected output</span><b id="eDims">—</b></div>
<div><span>Est. size (selected)</span><b id="eBytes">—</b></div>
</div>
<button id="exportBtn" class="primary expBtn">Convert & save</button>
<button id="stopBtn" class="danger stopBtn">Stop</button>
<div class="bar" id="bar"><i id="barI"></i></div>
<div class="status" id="status"></div>
<div class="note" id="note">Batches of 2+ save into a folder you pick (Chrome/Edge), otherwise they download one by one.</div>
</div>
</div>
</div>
<div class="panelbox" id="offlineNote" style="margin-top:14px;background:#11161d">
<h3 class="collap shut" data-target="offlineBody">Offline & HEIC support <span class="chev">▼</span></h3>
<div class="collapbody shut" id="offlineBody" style="color:var(--dim);font-size:12px;line-height:1.6">
<p style="margin:0 0 8px">This file is <b style="color:var(--txt)">fully self-contained</b> — no internet needed, nothing is uploaded. All the common formats (<b style="color:var(--txt)">JPEG / JFIF, PNG, WebP, AVIF, GIF, BMP</b>) are decoded and converted entirely by your browser.</p>
<p style="margin:0 0 8px"><b style="color:var(--txt)">HEIC</b> is the one format browsers can't decode on their own. This tool tries, in order & all offline: your browser's native decoder → the OS codec via WebCodecs → a local <code>heic2any.min.js</code>. Only if all three fail <i>and</i> you happen to be online does it try a CDN as a last resort — your images still never leave the machine either way. It works with no setup on:</p>
<ul style="margin:0 0 8px;padding-left:18px">
<li><b style="color:var(--txt)">Safari</b> (Mac/iPhone/iPad) — decodes HEIC natively, works instantly.</li>
<li><b style="color:var(--txt)">Chrome / Edge on Windows</b> — install the free <i>HEVC Video Extensions</i> from the Microsoft Store once, then HEIC decodes offline via the OS.</li>
<li><b style="color:var(--txt)">Chrome / Edge on macOS</b> — uses the system codec, usually works out of the box.</li>
</ul>
<p style="margin:0"><b style="color:var(--txt)">Guaranteed-offline HEIC on any browser:</b> download <code>heic2any.min.js</code> once (from <code>github.com/alexcorvi/heic2any</code>, the <code>/dist</code> folder) and save it <b style="color:var(--txt)">in the same folder as this HTML file</b>. The app auto-detects it and then decodes HEIC locally forever, with zero network.</p>
</div>
</div>
<div class="keys" style="margin-top:8px">
AVIF <i>output</i> depends on your browser (Chrome/Edge support it; Safari/Firefox may not). A few spec items (original file dates, Live Photo extraction, subfolder mirroring) need a desktop app.
</div>
</div>
<div id="pageDrop" aria-hidden="true">
<div class="box">
<div class="big">⇩</div>
<h2>Drop to add images</h2>
<p>Anywhere on the page · folders work too · nothing leaves this computer</p>
</div>
</div>
<canvas id="work" style="display:none"></canvas>
<script>
"use strict";
(function(){
/* ======================= helpers ======================= */
const $ = id => document.getElementById(id);
const clamp = (v,a,b) => Math.min(b, Math.max(a, v));
function human(bytes){
if(!isFinite(bytes) || bytes <= 0) return "\u2014";
if(bytes < 1024) return bytes + " B";
if(bytes < 1024*1024) return Math.round(bytes/1024) + " KB";
if(bytes < 1024*1024*1024) return (bytes/1024/1024).toFixed(bytes < 10*1024*1024 ? 2 : 1) + " MB";
return (bytes/1024/1024/1024).toFixed(2) + " GB";
}
function baseName(n){ return String(n||"image").replace(/\.[^.]+$/, "") || "image"; }
function safeName(s, fallback){
return String(s || fallback).replace(/[\\/:*?"<>|\x00-\x1f]+/g,"-").replace(/^\.+/,"").trim().slice(0,90) || fallback;
}
function extFor(mime){
return ({"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/avif":"avif","image/gif":"gif","application/pdf":"pdf"})[mime] || "img";
}
function isLossy(mime){ return mime==="image/jpeg" || mime==="image/webp" || mime==="image/avif"; }
function say(el, msg, kind){ el.textContent = msg || ""; el.className = "status" + (kind ? " " + kind : ""); }
function todayStr(){ const d = new Date(); const p = n => String(n).padStart(2,"0"); return d.getFullYear()+"-"+p(d.getMonth()+1)+"-"+p(d.getDate()); }
function wait(ms){ return new Promise(r => setTimeout(r, ms)); }
/* format support probe */
async function supportsMime(mime){
try{
const c = document.createElement("canvas"); c.width = c.height = 4;
const blob = await new Promise(r => c.toBlob(r, mime, 0.8));
return !!(blob && blob.type === mime);
}catch(e){ return false; }
}
/* ======================= state ======================= */
const items = []; // images, optionally with animated GIF frames
const PREVIEW_CAP = 1600; // longest side rendered in the preview; export is always full size
let previewTimer = 0, previewFrame = 0;
let bubbleHit=null,dragState=null;
let crop={l:0,r:0,t:0,b:0,angle:0};
let textLayers=[{id:1,mode:"bubble",text:"",pos:"bc",font:"Arial,Segoe UI,sans-serif",size:7,color:"#ffffff",bg:"#000000",pad:45,opacity:95,stroke:false,x:.5,y:.82,rot:0}],activeText=0,nextTextId=2;
let sel = -1, uid = 0, exporting = false, cancel = false, view = "preview";
let outFmt = "image/png";
const support = {};
/* ======================= collapsibles ======================= */
document.querySelectorAll("h3.collap").forEach(h => {
h.setAttribute("role","button");
h.setAttribute("tabindex","0");
h.setAttribute("aria-expanded", String(!h.classList.contains("shut")));
const toggle = () => {
h.classList.toggle("shut");
const b = $(h.dataset.target);
if(b) b.classList.toggle("shut");
h.setAttribute("aria-expanded", String(!h.classList.contains("shut")));
};
h.addEventListener("click", toggle);
h.addEventListener("keydown", e => {
if(e.key === "Enter" || e.key === " "){ e.preventDefault(); toggle(); }
});
});
/* ======================= loading files ======================= */
const drop = $("drop");
$("pickFiles").addEventListener("click", e => { e.stopPropagation(); $("fileInput").click(); });
$("pickFolder").addEventListener("click", e => { e.stopPropagation(); $("folderInput").click(); });
drop.addEventListener("click", e => { if(e.target.closest("button")) return; $("fileInput").click(); });
$("fileInput").addEventListener("change", e => { addFiles(e.target.files); e.target.value = ""; });
$("folderInput").addEventListener("change", e => { addFiles(e.target.files); e.target.value = ""; });
/* ---- collapse / expand the drop zone ---- */
let dropUserOpen = true; // user's explicit preference; auto-collapse only happens once
let dropAutoDone = false;
function setDropMini(mini){
drop.classList.toggle("mini", !!mini);
const t = $("dropToggle");
t.setAttribute("aria-expanded", String(!mini));
t.innerHTML = mini ? 'Add <span class="chev">▼</span>' : 'Hide <span class="chev">▲</span>';
}
$("dropToggle").addEventListener("click", e => {
e.stopPropagation();
dropUserOpen = drop.classList.contains("mini");
setDropMini(!dropUserOpen);
});
function autoCollapseDrop(){
if(dropAutoDone || !items.length) return;
dropAutoDone = true; dropUserOpen = false;
setDropMini(true);
}
/* ---- page-wide drag & drop ---- */
const pageDrop = $("pageDrop");
let dragDepth = 0;
const hasFiles = e => {
const t = e.dataTransfer && e.dataTransfer.types;
return !!t && (Array.prototype.indexOf.call(t, "Files") !== -1);
};
function showOverlay(on){
pageDrop.classList.toggle("show", !!on);
drop.classList.toggle("over", !!on);
if(!on) dragDepth = 0;
}
window.addEventListener("dragenter", e => {
if(!hasFiles(e)) return;
e.preventDefault(); dragDepth++; showOverlay(true);
});
window.addEventListener("dragover", e => {
if(!hasFiles(e)) return;
e.preventDefault();
try{ e.dataTransfer.dropEffect = "copy"; }catch(_){}
});
window.addEventListener("dragleave", e => {
if(!hasFiles(e)) return;
dragDepth = Math.max(0, dragDepth - 1);
if(dragDepth === 0) showOverlay(false);
});
window.addEventListener("drop", async e => {
if(!hasFiles(e)) return;
e.preventDefault(); showOverlay(false);
const dt = e.dataTransfer;
let files = null;
try{ files = await filesFromDataTransfer(dt); }catch(_){}
if(!files || !files.length) files = dt.files;
if(files && files.length) addFiles(files);
});
/* walk dropped folders (Chrome/Edge/Safari/Firefox all support webkitGetAsEntry) */
async function filesFromDataTransfer(dt){
const its = dt.items;
if(!its || !its.length || typeof DataTransferItem === "undefined" ||
!DataTransferItem.prototype.webkitGetAsEntry) return null;
const entries = [];
for(const it of its){ if(it.kind === "file"){ const en = it.webkitGetAsEntry && it.webkitGetAsEntry(); if(en) entries.push(en); } }
if(!entries.length) return null;
if(!entries.some(en => en.isDirectory)) return null; // plain files: use dt.files, it's faster
const out = [];
const readDir = dr => new Promise(res => {
const acc = [], rd = dr.createReader();
const step = () => rd.readEntries(batch => {
if(!batch.length) return res(acc);
acc.push(...batch); step();
}, () => res(acc));
step();
});
const walk = async en => {
if(en.isFile){ await new Promise(r => en.file(f => { out.push(f); r(); }, r)); }
else if(en.isDirectory){ for(const c of await readDir(en)) await walk(c); }
};
for(const en of entries) await walk(en);
return out;
}
function looksImage(f){
return (f.type && f.type.startsWith("image/")) ||
/\.(heic|heif|heics|jpe?g|jfif|pjpeg|pjp|png|webp|gif|bmp|tiff?|avif|ico)$/i.test(f.name);
}
let _rTimer = 0;
function renderSoon(){ if(_rTimer) return; _rTimer = setTimeout(() => { _rTimer = 0; render(); }, 120); }
/* paste an image straight from the clipboard */
window.addEventListener("paste", e => {
const f = e.clipboardData && e.clipboardData.files;
if(f && f.length){ e.preventDefault(); addFiles(f); }
});
async function addFiles(fileList){
if(exporting){ say($("status"), "Finish or stop the current export before adding more images.", "err"); return; }
const files = Array.from(fileList).filter(looksImage);
if(!files.length){ say($("status"), "Those files are not images. Add HEIC, JPEG, PNG, WebP, GIF or BMP.", "err"); return; }
say($("status"), "Reading " + files.length + (files.length === 1 ? " image\u2026" : " images\u2026"));
const firstNew = items.length;
for(const f of files){
items.push({ id: ++uid, file: f, name: f.name, selected: true, status: "queued", gifTotalFrames:0, gifTruncated:false,
bitmap: null, frames: null, delays: null, loops: 0, w: 0, h: 0, outName: "", outSize: 0, thumbUrl: "", err: "" });
}
render();
autoCollapseDrop();
const pending = items.slice(firstNew);
const worker = async () => {
while(pending.length){
const it = pending.shift();
if(!it.bitmap && it.status !== "error") await decode(it);
renderSoon();
}
};
await Promise.all([worker(), worker(), worker()]);
clearTimeout(_rTimer); _rTimer = 0; render();
if(sel < 0 && items.length) sel = 0;
if(firstNew === 0 && files.length && files.every(f => /\.gif$/i.test(f.name) || f.type === "image/gif")){
outFmt = "image/gif";
document.querySelectorAll("#fmtSeg button").forEach(x => x.classList.toggle("on", x.dataset.fmt === outFmt));
syncFmtUI();
}
drawPreview();
const bad = items.filter(it => it.status === "error").length;
say($("status"),
items.length + " image" + (items.length===1?"":"s") + " ready" + (bad ? " \u00b7 " + bad + " could not be read" : "") + ".",
bad ? "err" : "ok");
updateEstimate();
}
const isHeic = f => /\.(heic|heif)$/i.test(f.name) || f.type === "image/heic" || f.type === "image/heif" || f.type === "image/heic-sequence";
/* ---- HEIC engine (optional, offline-first) ---- */
let heicPromise = null, heicSource = "";
function loadScript(src){
return new Promise((res, rej) => {
const s = document.createElement("script");
s.src = src; s.async = true;
s.onload = () => res(true);
s.onerror = () => rej(new Error("failed " + src));
document.head.appendChild(s);
});
}
function ensureHeic(){
if(typeof heic2any !== "undefined") return Promise.resolve(true);
if(heicPromise) return heicPromise;
const sources = [
{ url: "heic2any.min.js", local: true },
{ url: "libheif/heic2any.min.js", local: true },
{ url: "https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js", local: false },
{ url: "https://unpkg.com/heic2any@0.0.4/dist/heic2any.min.js", local: false }
];
heicPromise = (async () => {
for(const s of sources){
try{ await loadScript(s.url); if(typeof heic2any !== "undefined"){ heicSource = s.local ? "local file" : "CDN"; return true; } }
catch(e){ /* try next */ }
}
heicPromise = null;
throw new Error("no HEIC engine available offline");
})();
return heicPromise;
}
async function decodeViaWebCodecs(blob){
if(typeof ImageDecoder === "undefined") return null;
try{
const type = blob.type && blob.type !== "" ? blob.type : "image/heic";
if(ImageDecoder.isTypeSupported){
const ok = await ImageDecoder.isTypeSupported(type).catch(() => false);
if(!ok) return null;
}
const buf = await blob.arrayBuffer();
const dec = new ImageDecoder({ data: buf, type });
const { image } = await dec.decode();
const bmp = await createImageBitmap(image);
try{ image.close && image.close(); }catch(_){}
return bmp;
}catch(e){ return null; }
}
async function decodeNative(blob){
const useExif = $("autoExif").checked;
try{
return await createImageBitmap(blob, useExif ? { imageOrientation: "from-image" } : {});
}catch(e){
try{ return await loadViaImg(blob); }
catch(e2){ return null; }
}
}
async function decode(it){
it.status = "decoding"; renderSoon();
try{
let bmp = await decodeNative(it.file);
if(!bmp && isHeic(it.file)) bmp = await decodeViaWebCodecs(it.file);
if(!bmp && isHeic(it.file)){
try{
await ensureHeic();
let out;
try{ out = await heic2any({ blob: it.file, toType: "image/jpeg", quality: 0.92 }); }
catch(e){
if(/already browser readable/i.test(e && e.message || "")){ bmp = await decodeNative(it.file); }
else { out = await heic2any({ blob: it.file, toType: "image/png" }); }
}
if(!bmp && out){ bmp = await decodeNative(Array.isArray(out) ? out[0] : out); }
}catch(engineErr){}
}
if(!bmp) throw new Error(isHeic(it.file)
? "HEIC needs a codec this browser lacks — see the offline HEIC note, or open in Safari"
: "this browser can't read that format");
it.bitmap = bmp; it.w = bmp.width; it.h = bmp.height;
if(/\.gif$/i.test(it.name) || it.file.type === "image/gif") await decodeGifFrames(it);
it.status = "ready";
it.thumbUrl = makeThumb(bmp);
}catch(e){
it.status = "error"; it.err = e.message || "could not decode";
}
}
async function decodeGifFrames(it){
if(typeof ImageDecoder === "undefined") return false;
let dec=null,frames=[];
try{
const ok=!ImageDecoder.isTypeSupported||await ImageDecoder.isTypeSupported("image/gif");if(!ok)return false;
dec=new ImageDecoder({data:await it.file.arrayBuffer(),type:"image/gif",preferAnimation:true});await dec.tracks.ready;
const track=dec.tracks.selectedTrack,total=Number(track&&track.frameCount)||1,count=Math.min(total,600);it.gifTotalFrames=total;it.gifTruncated=total>600;if(count<2)return false;
const delays=[];
for(let i=0;i<count;i++){const r=await dec.decode({frameIndex:i,completeFramesOnly:true}),vf=r.image;frames.push(await createImageBitmap(vf));delays.push(Math.max(20,Math.round((Number(vf.duration)||100000)/1000)));try{vf.close()}catch(_){}if(i%10===0)await wait(0);}
const old=it.bitmap;it.frames=frames;it.delays=delays;it.loops=track.repetitionCount;it.bitmap=frames[0];it.w=frames[0].width;it.h=frames[0].height;if(old&&old!==it.bitmap){try{old.close&&old.close()}catch(_){}}return true;
}catch(e){for(const f of frames){try{f.close&&f.close()}catch(_){}}it.frames=null;it.delays=null;return false;}finally{try{dec&&dec.close()}catch(_){}}
}
function loadViaImg(blob){
return new Promise((res, rej) => {
const url = URL.createObjectURL(blob), img = new Image();
img.onload = () => { res(img); setTimeout(()=>URL.revokeObjectURL(url), 5000); };
img.onerror = () => { URL.revokeObjectURL(url); rej(new Error("decode failed")); };
img.src = url;
});
}
function makeThumb(bmp){
const c = document.createElement("canvas");
const w = 160, h = 120;
c.width = w; c.height = h;
const x = c.getContext("2d");
x.fillStyle = "#07090c"; x.fillRect(0,0,w,h);
const sc = Math.max(w/bmp.width, h/bmp.height);
const dw = bmp.width*sc, dh = bmp.height*sc;
x.drawImage(bmp, (w-dw)/2, (h-dh)/2, dw, dh);
return c.toDataURL("image/jpeg", 0.72);
}
/* ======================= transforms ======================= */
let rot = 0, flipH = false, flipV = false;
$("rotL").addEventListener("click", () => { rot = (rot + 270) % 360; drawPreview(); updateEstimate(); });
$("rotR").addEventListener("click", () => { rot = (rot + 90) % 360; drawPreview(); updateEstimate(); });
$("flipH").addEventListener("click", () => { flipH = !flipH; drawPreview(); });
$("flipV").addEventListener("click", () => { flipV = !flipV; drawPreview(); });
$("resetAdj").addEventListener("click", () => { rot = 0; flipH = flipV = false; drawPreview(); updateEstimate(); });
$("autoExif").addEventListener("change", async () => {
for(const it of items){
if(!it.bitmap) continue;
freeItem(it);
it.bitmap = null; it.frames = null; it.delays = null; it.status = "queued";
}
render();
for(const it of items) if(it.status !== "error") { await decode(it); renderSoon(); }
clearTimeout(_rTimer); _rTimer = 0; render();
drawPreview();
});
function targetSize(sw, sh){
const mode = document.querySelector("#resizeMode button.on").dataset.m;
let w = sw, h = sh;
if(mode === "pct"){ const p = (+$("pct").value||100)/100; w = sw*p; h = sh*p; }
else if(mode === "px"){
const pw = +$("pxW").value||0, ph = +$("pxH").value||0;
if(pw && ph){ w = pw; h = ph; }
else if(pw){ w = pw; h = sh*pw/sw; }
else if(ph){ h = ph; w = sw*ph/sh; }
}
else if(mode === "max"){
const m = +$("maxPreset").value||1600;
const s = Math.min(1, m/Math.max(sw, sh));
w = sw*s; h = sh*s;
}
return { w: Math.max(1, Math.round(w)), h: Math.max(1, Math.round(h)) };
}
/* Work out the exact output geometry without drawing anything.
Used for the size badges and the estimate, so we no longer re-render
the full-resolution image just to learn how big it will be. */
function outputGeom(bmp){
const swapped=(rot===90||rot===270);
const cl=Math.min(.45,crop.l/100),cr=Math.min(.45,crop.r/100),ct=Math.min(.45,crop.t/100),cb=Math.min(.45,crop.b/100);
const srcW=Math.max(1,bmp.width*(1-cl-cr)),srcH=Math.max(1,bmp.height*(1-ct-cb));
const baseW=swapped?srcH:srcW,baseH=swapped?srcW:srcH,t=targetSize(baseW,baseH);
let extraTop=0,extraBottom=0;
for(const o of textLayers){if(!o.text)continue;if(o.mode==="topbox")extraTop=Math.max(extraTop,captionExtraFor(o,t.w,t.h));if(o.mode==="bottombox")extraBottom=Math.max(extraBottom,captionExtraFor(o,t.w,t.h));}
return {swapped,cl,ct,srcW,srcH,tw:t.w,th:t.h,extraTop,extraBottom,w:t.w,h:t.h+extraTop+extraBottom};
}
/* cap = longest side to render at (preview only). 0 = full resolution. */
function renderToCanvas(bmp,showControls=false,cap=0){
const G=outputGeom(bmp);
const k=(cap&&Math.max(G.w,G.h)>cap)?cap/Math.max(G.w,G.h):1;
const tw=Math.max(1,Math.round(G.tw*k)),th=Math.max(1,Math.round(G.th*k));
const extraTop=Math.round(G.extraTop*k),extraBottom=Math.round(G.extraBottom*k);
const cv=$("work");cv.width=tw;cv.height=th+extraTop+extraBottom;
const g=cv.getContext("2d");g.imageSmoothingEnabled=true;g.imageSmoothingQuality="high";
const indexedPng=(outFmt==="image/png"&&(+$("pngColors").value||0)>0);
if(outFmt==="image/jpeg"||outFmt==="application/pdf"||indexedPng||extraTop||extraBottom){
g.fillStyle=(extraTop||extraBottom)?"#000":"#fff";g.fillRect(0,0,cv.width,cv.height);
}
const sx=bmp.width*G.cl,sy=bmp.height*G.ct;
g.save();g.beginPath();g.rect(0,extraTop,tw,th);g.clip();
g.translate(tw/2,extraTop+th/2);
g.rotate((rot+crop.angle)*Math.PI/180);
/* straightening rotates inside a fixed frame, which would expose empty
corners — zoom just enough to keep the frame covered. */
if(crop.angle){
const ar=Math.abs(crop.angle)*Math.PI/180,ca=Math.cos(ar),sa=Math.sin(ar);
const cover=Math.max((tw*ca+th*sa)/tw,(tw*sa+th*ca)/th);
g.scale(cover,cover);
}
g.scale(flipH?-1:1,flipV?-1:1);
const drawW=G.swapped?th:tw,drawH=G.swapped?tw:th;
g.drawImage(bmp,sx,sy,G.srcW,G.srcH,-drawW/2,-drawH/2,drawW,drawH);
g.restore();
if(showControls) bubbleHit=null;
for(let i=0;i<textLayers.length;i++)drawTextLayer(g,textLayers[i],cv.width,cv.height,extraTop,th,extraTop,extraBottom,showControls&&i===activeText);
return cv;
}
function captionExtraFor(o,W,H){const size=Math.max(14,Math.round(Math.min(W,H)*(o.size/100))),pad=Math.round(size*(o.pad/100)),tmp=document.createElement("canvas").getContext("2d");tmp.font="700 "+size+"px "+o.font;return wrapLines(tmp,o.text,Math.max(80,W-pad*4)).length*Math.round(size*1.18)+pad*2;}
function wrapLines(g,text,maxW){
const out=[]; for(const para of text.split(/\n/)){ const words=para.split(/\s+/); let line="";
for(const w of words){ const test=line?line+" "+w:w; if(line&&g.measureText(test).width>maxW){out.push(line);line=w;}else line=test; } out.push(line); }
return out.length?out:[""];
}
function drawTextLayer(g,o,W,H,imageY,imageH,extraTop,extraBottom,isActive){
if(!o||o.mode==="none"||!o.text)return;const mode=o.mode,text=mode==="meme"?o.text.toUpperCase():o.text,size=Math.max(14,Math.round(Math.min(W,imageH)*(o.size/100))),basePad=Math.round(size*(o.pad/100)),pad=basePad;
g.save();g.globalAlpha=o.opacity/100;const family=mode==="meme"?"Impact,Arial Black,sans-serif":o.font;g.font=(mode==="meme"?"900 ":"700 ")+size+"px "+family;g.textBaseline="alphabetic";g.textAlign="left";const maxW=Math.max(80,W-basePad*4),lines=wrapLines(g,text,maxW),metrics=lines.map(x=>g.measureText(x)),ascent=Math.max(...metrics.map(m=>m.actualBoundingBoxAscent||size*.8)),descent=Math.max(...metrics.map(m=>m.actualBoundingBoxDescent||size*.2)),gap=Math.round(size*.18),lh=ascent+descent+gap,tw=Math.min(maxW,Math.max(...metrics.map(m=>m.width))),th=lines.length*(ascent+descent)+(lines.length-1)*gap;
if(mode==="topbox"||mode==="bottombox"){const y=mode==="topbox"?0:H-extraBottom;g.fillStyle="#000";g.fillRect(0,y,W,mode==="topbox"?extraTop:extraBottom);g.fillStyle=o.color;g.textAlign="center";lines.forEach((ln,i)=>g.fillText(ln,W/2,y+pad+ascent+i*lh));g.restore();return;}
let x=o.x*W,y=imageY+o.y*imageH;if(mode!=="bubble"){const pos=o.pos;x=pad+tw/2;y=imageY+pad+th/2;if(pos.endsWith("c"))x=W/2;else if(pos.endsWith("r"))x=W-pad-tw/2;if(pos.startsWith("b"))y=imageY+imageH-pad-th/2;else if(pos==="c"){x=W/2;y=imageY+imageH/2;}}
g.translate(x,y);g.rotate(o.rot*Math.PI/180);
const lineWidths=lines.map(ln=>g.measureText(ln).width);
const bubbleLineH=ascent+descent+pad*2;
const bubbleStep=ascent+descent+gap;
const bubbleTotalH=lines.length===1?bubbleLineH:bubbleLineH+(lines.length-1)*bubbleStep;
if(mode==="bubble"){
g.fillStyle=o.bg;
lines.forEach((ln,i)=>{
const bw=lineWidths[i]+pad*2;
const by=-bubbleTotalH/2+i*bubbleStep;
const radius=Math.min(bubbleLineH/2,Math.max(12,bubbleLineH*.34));
roundRect(g,-bw/2,by,bw,bubbleLineH,radius);g.fill();
});
}
g.fillStyle=o.color;const stroke=o.stroke||mode==="meme";if(stroke){g.strokeStyle="#000";g.lineWidth=Math.max(2,size*.09);g.lineJoin="round";}
lines.forEach((ln,i)=>{const lx=-lineWidths[i]/2,ly=(mode==="bubble"?-bubbleTotalH/2+pad+ascent+i*bubbleStep:-th/2+ascent+i*lh);if(stroke)g.strokeText(ln,lx,ly);g.fillText(ln,lx,ly);});
if(isActive&&mode==="bubble"){
const hitW=Math.max(...lineWidths)+pad*2,hitH=bubbleTotalH;
bubbleHit={cx:x,cy:y,w:hitW,h:hitH,a:o.rot*Math.PI/180,handleY:-hitH/2-size*.8,resizeX:hitW/2,resizeY:hitH/2};
g.globalAlpha=1;g.strokeStyle="#4cc2ff";g.lineWidth=Math.max(2,W/400);g.setLineDash([6,4]);g.strokeRect(-hitW/2,-hitH/2,hitW,hitH);g.setLineDash([]);g.beginPath();g.arc(0,bubbleHit.handleY,Math.max(7,size*.13),0,Math.PI*2);g.fillStyle="#4cc2ff";g.fill();const hs=Math.max(10,size*.18);g.fillRect(bubbleHit.resizeX-hs/2,bubbleHit.resizeY-hs/2,hs,hs);
}g.restore();
}
function roundRect(g,x,y,w,h,r){r=Math.min(r,w/2,h/2);g.beginPath();g.moveTo(x+r,y);g.arcTo(x+w,y,x+w,y+h,r);g.arcTo(x+w,y+h,x,y+h,r);g.arcTo(x,y+h,x,y,r);g.arcTo(x,y,x+w,y,r);g.closePath();}
/* ======================= preview ======================= */
function drawPreview(){
const cv = $("preview"), g = cv.getContext("2d");
const it = items[sel];
clearTimeout(previewTimer); previewTimer = 0;
if(!it || !it.bitmap){
cv.width = 640; cv.height = 360;
g.fillStyle = "#000"; g.fillRect(0,0,cv.width,cv.height);
$("srcBadge").textContent = it ? (it.status === "error" ? "Could not decode this file" : "Decoding\u2026") : "No image selected";
$("outBadge").textContent = "";
return;
}
const anim = it.frames && it.frames.length > 1;
const frame = anim ? it.frames[previewFrame % it.frames.length] : it.bitmap;
const out = renderToCanvas(frame, true, PREVIEW_CAP);
cv.width = out.width; cv.height = out.height;
g.drawImage(out, 0, 0);
const G = outputGeom(frame);
$("srcBadge").textContent = it.name + " \u00b7 " + it.w + "\u00d7" + it.h +
(isHeic(it.file) ? " \u00b7 HEIC" : "") + (anim ? " \u00b7 " + it.frames.length + " frames" : "");
$("outBadge").textContent = G.w + "\u00d7" + G.h + " \u00b7 " + fmtLabel(outFmt) +
(out.width < G.w ? " \u00b7 preview scaled" : "");
/* play animated GIFs in the preview instead of freezing on frame 1 */
if(anim && !dragState && view === "preview"){
const sp = (+$("gifSpeed").value || 100) / 100;
const d = Math.max(20, (it.delays && it.delays[previewFrame % it.frames.length] || 100) / sp);
previewTimer = setTimeout(() => { previewFrame++; drawPreview(); }, d);
}
}
function fmtLabel(m){ return ({"image/png":"PNG","image/jpeg":"JPEG","image/webp":"WebP","image/avif":"AVIF","image/gif":"GIF","application/pdf":"PDF"})[m] || m; }
/* ======================= view toggle ======================= */
$("viewTabs").addEventListener("click", e => {
const b = e.target.closest("button"); if(!b) return;
view = b.dataset.v;
document.querySelectorAll("#viewTabs button").forEach(x => x.classList.toggle("on", x === b));
$("previewView").style.display = view === "preview" ? "block" : "none";
$("gridView").style.display = view === "grid" ? "block" : "none";
$("listView").style.display = view === "grid" ? "none" : "block";
if(view === "grid") renderGrid(); else drawPreview();
});
/* ======================= selection helpers ======================= */
function selectedReady(){ return items.filter(it => it.selected && it.status !== "error" && (it.bitmap || (it.frames && it.frames[0]))); }
$("selAll").addEventListener("click", () => { items.forEach(it => { if(it.status !== "error") it.selected = true; }); render(); });
$("selNone").addEventListener("click", () => { items.forEach(it => it.selected = false); render(); });
/* ======================= queue rendering ======================= */
function render(){
$("qCount").textContent = items.length + (items.length===1?" image":" images") +
(items.length ? " \u00b7 " + selectedReady().length + " ticked" : "");
renderList();
if(view === "grid") renderGrid();
updateEstimate();
}
function renderList(){
const list = $("qList");
if(!items.length){ list.innerHTML = '<div class="empty">No images yet. Drop files above and they will appear here in order.</div>'; drawPreview(); return; }
list.textContent = "";
items.forEach((it, i) => {
const row = document.createElement("div");
row.className = "qrow" + (i === sel ? " on" : "");
row.addEventListener("click", () => { sel = i; previewFrame = 0; drawPreview(); render(); });
const chk = document.createElement("input");
chk.type = "checkbox"; chk.checked = !!it.selected; chk.title = "Include in conversion";
chk.disabled = it.status === "error";
chk.addEventListener("click", ev => { ev.stopPropagation(); it.selected = chk.checked; render(); });
row.appendChild(chk);
if(it.thumbUrl){ const img = document.createElement("img"); img.className = "qthumb"; img.src = it.thumbUrl; row.appendChild(img); }
else { const ph = document.createElement("div"); ph.className = "qthumb ph"; ph.textContent = it.status === "error" ? "!" : "\u2026"; row.appendChild(ph); }
const meta = document.createElement("div"); meta.className = "qmeta";
const nm = document.createElement("div"); nm.className = "qname"; nm.textContent = it.name; nm.title = it.name;
const sub = document.createElement("div"); sub.className = "qsub";
sub.textContent = it.status === "error" ? ("error: " + it.err)
: it.w ? (it.w + "\u00d7" + it.h + " \u00b7 " + human(it.file.size)) : "\u2026";
meta.appendChild(nm); meta.appendChild(sub);
row.appendChild(meta);
const st = document.createElement("div");
st.className = "qstate " + (it.status === "done" ? "done" : it.status === "error" ? "err" : (it.status==="decoding"||it.status==="working") ? "work" : "");
st.textContent = it.status === "done" ? human(it.outSize)
: it.status === "error" ? "failed"
: it.status === "working" ? "\u2026"
: it.status === "decoding" ? "reading" : "ready";
row.appendChild(st);
const x = document.createElement("button");
x.className = "qx danger ghost"; x.innerHTML = "×"; x.title = "Remove";
x.addEventListener("click", ev => { ev.stopPropagation(); removeAt(i); });
row.appendChild(x);
list.appendChild(row);
});
}
function renderGrid(){
const g = $("imgrid");
if(!items.length){ g.innerHTML = '<div class="empty">No images yet.</div>'; return; }
g.textContent = "";
items.forEach((it, i) => {
const card = document.createElement("div");
card.className = "gcard" + (i === sel ? " on" : "");
card.addEventListener("click", () => { sel = i; previewFrame = 0; if(view==="preview") drawPreview(); render(); });
const chk = document.createElement("input");
chk.type = "checkbox"; chk.className = "gchk"; chk.checked = !!it.selected;
chk.disabled = it.status === "error"; chk.title = "Include in conversion";
chk.addEventListener("click", ev => { ev.stopPropagation(); it.selected = chk.checked; render(); });
card.appendChild(chk);
const x = document.createElement("button");
x.className = "gx"; x.innerHTML = "×"; x.title = "Remove";
x.addEventListener("click", ev => { ev.stopPropagation(); removeAt(i); });
card.appendChild(x);
if(it.thumbUrl){ const img = document.createElement("img"); img.src = it.thumbUrl; card.appendChild(img); }
else { const ph = document.createElement("div"); ph.className = "gph"; ph.textContent = it.status === "error" ? "!" : "\u2026"; card.appendChild(ph); }
if(it.status !== "queued" && it.status !== "ready"){
const st = document.createElement("div");
st.className = "gstate " + (it.status === "done" ? "done" : it.status === "error" ? "err" : "work");
st.textContent = it.status === "done" ? human(it.outSize) : it.status === "error" ? "failed" : it.status === "decoding" ? "reading" : "\u2026";
card.appendChild(st);
}
const nm = document.createElement("div"); nm.className = "gname"; nm.textContent = it.name; nm.title = it.name;
card.appendChild(nm);
g.appendChild(card);
});
}
function freeItem(it){
if(!it) return;
for(const b of new Set([it.bitmap, ...(it.frames || [])])){ try{ b && b.close && b.close(); }catch(_){} }
}
function removeAt(i){
if(exporting) return;
freeItem(items[i]);
items.splice(i, 1);
if(sel >= items.length) sel = items.length - 1;
if(!items.length){ dropAutoDone = false; setDropMini(false); }
render(); if(view==="preview") drawPreview();
}
$("clearAll").addEventListener("click", () => { if(exporting) return; items.forEach(freeItem); items.length = 0; sel = -1; dropAutoDone = false; setDropMini(false); render(); drawPreview(); say($("status"),""); });
$("clearDone").addEventListener("click", () => {
if(exporting) return;
for(let i = items.length-1; i>=0; i--) if(items[i].status === "done") removeAt(i);
});
/* ======================= settings wiring ======================= */
function syncFmtUI(){
const lossy = isLossy(outFmt);
/* PDF pages are embedded as JPEG, so the quality slider matters there too. */
$("qualityRow").style.display = (lossy || outFmt === "application/pdf") ? "flex" : "none";
$("targetChk").style.display = lossy ? "flex" : "none";
$("targetRow").style.display = (lossy && $("targetOn").checked) ? "flex" : "none";
$("pngOpts").style.display = outFmt === "image/png" ? "block" : "none";
$("ditherChk").style.display = (outFmt === "image/png" && (+$("pngColors").value||0) > 0) ? "flex" : "none";
let hint = "";
if(outFmt === "image/png"){
hint = (+$("pngColors").value||0) > 0
? "Indexed PNG (like Photoshop PNG-8) — much smaller, but limited to the chosen palette; photos may posterise. Keeps sharp graphics crisp."
: "Lossless 24-bit PNG (like Photoshop PNG-24) — full quality, no colour loss. Uses adaptive filtering so files are far smaller than a plain PNG. Transparency is preserved.";
}
else if(outFmt === "image/jpeg") hint = "JPEG is best for photos. No transparency — transparent areas become white.";
else if(outFmt === "image/webp") hint = "WebP gives smaller files than JPEG at similar quality, with transparency support.";
else if(outFmt === "image/avif") hint = support["image/avif"] === false ? "\u26a0 Your browser can\u2019t encode AVIF — try Chrome or Edge, or pick WebP." : "AVIF is the smallest for photos, but slower to encode. Chrome/Edge only.";
else if(outFmt === "image/gif") hint = "Animated GIF export keeps animation when its frames were decoded; otherwise it exports one GIF frame. Colours are reduced to a web-safe palette.";
else if(outFmt === "application/pdf") hint = "Each ticked image becomes one PDF page (embedded as JPEG), scaled to fit A4 in its own orientation. The quality slider controls the page images.";
$("fmtHint").textContent = hint;
}
$("fmtSeg").addEventListener("click", async e => {
if(exporting) return;
const b = e.target.closest("button"); if(!b || b.disabled) return;
document.querySelectorAll("#fmtSeg button").forEach(x => x.classList.toggle("on", x === b));
outFmt = b.dataset.fmt;
syncFmtUI();
drawPreview(); updateEstimate();
});
$("quality").addEventListener("input", () => { $("qualityL").textContent = $("quality").value; updateEstimate(); });
$("targetOn").addEventListener("change", () => { $("targetRow").style.display = ($("targetOn").checked && isLossy(outFmt)) ? "flex" : "none"; updateEstimate(); });
["targetSize","targetUnit"].forEach(id => $(id).addEventListener("input", updateEstimate));
$("pngColors").addEventListener("change", () => { syncFmtUI(); drawPreview(); updateEstimate(); });
$("pngDither").addEventListener("change", updateEstimate);
$("resizeMode").addEventListener("click", e => {
const b = e.target.closest("button"); if(!b) return;
document.querySelectorAll("#resizeMode button").forEach(x => x.classList.toggle("on", x === b));
const m = b.dataset.m;
$("pctRow").style.display = m === "pct" ? "flex" : "none";
$("pxRows").style.display = m === "px" ? "block" : "none";
$("maxRow").style.display = m === "max" ? "flex" : "none";
if(m === "px" && items[sel]){ const it = items[sel]; $("pxW").value = it.w; $("pxH").value = it.h; }
drawPreview(); updateEstimate();
});
["pct","maxPreset"].forEach(id => $(id).addEventListener("input", () => { drawPreview(); updateEstimate(); }));
/* the naming segment had no handler at all, so "Template" could never be chosen */
$("nameMode").addEventListener("click", e => {
const b = e.target.closest("button"); if(!b) return;
document.querySelectorAll("#nameMode button").forEach(x => x.classList.toggle("on", x === b));
$("tplRows").style.display = b.dataset.m === "tpl" ? "block" : "none";
});
$("pxW").addEventListener("input", () => { if($("lockAr").checked && items[sel]){ const it = items[sel]; $("pxH").value = Math.round((+$("pxW").value||1) * it.h / it.w); } drawPreview(); updateEstimate(); });
$("pxH").addEventListener("input", () => { if($("lockAr").checked && items[sel]){ const it = items[sel]; $("pxW").value = Math.round((+$("pxH").value||1) * it.w / it.h); } drawPreview(); updateEstimate(); });
function activeLayer(){return textLayers[activeText];}
function saveLayerFromUI(){const o=activeLayer();if(!o)return;o.mode=$("textMode").value;o.text=$("wmText").value;o.pos=$("wmPos").value;o.font=$("wmFont").value;o.size=+$("wmSize").value;o.color=$("wmColor").value;o.bg=$("wmBg").value;o.pad=+$("wmPad").value;o.opacity=+$("wmOpacity").value;o.stroke=$("wmStroke").checked;}
function loadLayerToUI(){const o=activeLayer();if(!o)return;$("textMode").value=o.mode;$("wmText").value=o.text;$("wmPos").value=o.pos;$("wmFont").value=o.font;$("wmSize").value=o.size;$("wmColor").value=o.color;$("wmBg").value=o.bg;$("wmPad").value=o.pad;$("wmOpacity").value=o.opacity;$("wmStroke").checked=o.stroke;$("wmSizeL").textContent=o.size+"%";$("wmPadL").textContent=o.pad+"%";$("wmOpacityL").textContent=o.opacity+"%";renderTextLayerList();drawPreview();updateEstimate();}
function renderTextLayerList(){const l=$("textLayerList");l.textContent="";textLayers.forEach((o,i)=>{const op=document.createElement("option");op.value=i;op.textContent=(i+1)+". "+(o.mode==="none"?"None":o.mode)+" · "+(o.text||"empty").slice(0,22);op.selected=i===activeText;l.appendChild(op);});}
["textMode","wmText","wmPos","wmFont","wmSize","wmColor","wmBg","wmPad","wmStroke","wmOpacity"].forEach(id=>$(id).addEventListener("input",()=>{saveLayerFromUI();$("wmSizeL").textContent=$("wmSize").value+"%";$("wmPadL").textContent=$("wmPad").value+"%";$("wmOpacityL").textContent=$("wmOpacity").value+"%";renderTextLayerList();drawPreview();updateEstimate();}));
$("textLayerList").onchange=e=>{saveLayerFromUI();activeText=+e.target.value;loadLayerToUI();};
$("addTextLayer").onclick=()=>{saveLayerFromUI();textLayers.push({id:nextTextId++,mode:"bubble",text:"",pos:"bc",font:"Arial,Segoe UI,sans-serif",size:7,color:"#ffffff",bg:"#000000",pad:45,opacity:95,stroke:false,x:.5,y:.82,rot:0});activeText=textLayers.length-1;loadLayerToUI();};
$("dupTextLayer").onclick=()=>{saveLayerFromUI();const n={...activeLayer(),id:nextTextId++,x:Math.min(.95,activeLayer().x+.04),y:Math.min(.95,activeLayer().y+.04)};textLayers.push(n);activeText=textLayers.length-1;loadLayerToUI();};
$("delTextLayer").onclick=()=>{if(textLayers.length===1){textLayers[0]={id:nextTextId++,mode:"bubble",text:"",pos:"bc",font:"Arial,Segoe UI,sans-serif",size:7,color:"#ffffff",bg:"#000000",pad:45,opacity:95,stroke:false,x:.5,y:.82,rot:0};activeText=0;}else{textLayers.splice(activeText,1);activeText=Math.max(0,activeText-1);}loadLayerToUI();};
$("textMode").addEventListener("change",()=>{if($("textMode").value==="meme"){$("wmFont").value="Impact,Arial Black,sans-serif";}saveLayerFromUI();drawPreview();});
function canvasPoint(e){const c=$("preview"),r=c.getBoundingClientRect();return{x:(e.clientX-r.left)*c.width/r.width,y:(e.clientY-r.top)*c.height/r.height};}
function localHit(p,h){const dx=p.x-h.cx,dy=p.y-h.cy,ca=Math.cos(-h.a),sa=Math.sin(-h.a);return{x:dx*ca-dy*sa,y:dx*sa+dy*ca};}
$("preview").addEventListener("pointerdown",e=>{const o=activeLayer();if(!o||o.mode!=="bubble"||!bubbleHit)return;const p=canvasPoint(e),l=localHit(p,bubbleHit),hr=Math.max(14,bubbleHit.h*.15);if(Math.hypot(l.x,l.y-bubbleHit.handleY)<hr)dragState={kind:"rotate"};else if(Math.hypot(l.x-bubbleHit.resizeX,l.y-bubbleHit.resizeY)<hr)dragState={kind:"resize",startDist:Math.hypot(l.x,l.y),startSize:o.size};else if(Math.abs(l.x)<=bubbleHit.w/2&&Math.abs(l.y)<=bubbleHit.h/2)dragState={kind:"move",ox:p.x-bubbleHit.cx,oy:p.y-bubbleHit.cy};if(dragState){e.preventDefault();$("preview").setPointerCapture(e.pointerId);}});
$("preview").addEventListener("pointermove",e=>{if(!dragState)return;const p=canvasPoint(e),o=activeLayer();if(!o)return;if(dragState.kind==="move"){o.x=Math.max(0,Math.min(1,(p.x-dragState.ox)/$("preview").width));o.y=Math.max(0,Math.min(1,(p.y-dragState.oy)/$("preview").height)); }else if(dragState.kind==="resize"){const l=localHit(p,bubbleHit),ratio=Math.hypot(l.x,l.y)/Math.max(1,dragState.startDist);o.size=Math.max(2,Math.min(30,dragState.startSize*ratio));$("wmSize").value=o.size;$("wmSizeL").textContent=o.size.toFixed(1)+"%";}else{o.rot=Math.round(Math.atan2(p.y-bubbleHit.cy,p.x-bubbleHit.cx)*180/Math.PI+90);}drawPreview();});
function endBubbleDrag(){if(!dragState)return;dragState=null;renderTextLayerList();updateEstimate();drawPreview();}
$("preview").addEventListener("pointerup",endBubbleDrag);
$("preview").addEventListener("pointercancel",endBubbleDrag);
$("preview").addEventListener("lostpointercapture",()=>{if(dragState){dragState=null;renderTextLayerList();updateEstimate();drawPreview();}});
["cropL","cropR","cropT","cropB","straighten"].forEach(id=>$(id).addEventListener("input",()=>{crop.l=+$("cropL").value;crop.r=+$("cropR").value;crop.t=+$("cropT").value;crop.b=+$("cropB").value;crop.angle=+$("straighten").value;$("cropLL").textContent=crop.l+"%";$("cropRL").textContent=crop.r+"%";$("cropTL").textContent=crop.t+"%";$("cropBL").textContent=crop.b+"%";$("straightenL").textContent=crop.angle+"°";drawPreview();updateEstimate();}));
$("resetCrop").onclick=()=>{crop={l:0,r:0,t:0,b:0,angle:0};$("cropPreset").value="free";["cropL","cropR","cropT","cropB","straighten"].forEach(id=>$(id).value=0);["cropLL","cropRL","cropTL","cropBL"].forEach(id=>$(id).textContent="0%");$("straightenL").textContent="0°";drawPreview();updateEstimate();};
$("cropPreset").onchange=()=>{const v=$("cropPreset").value,it=items[sel];
if(v==="free"){["cropL","cropR","cropT","cropB"].forEach(id=>$(id).value=0);$("cropL").dispatchEvent(new Event("input"));return;}
if(!it)return;const [a,b]=v.split(":").map(Number),target=a/b,cur=it.w/it.h;let lr=0,tb=0;if(cur>target)lr=(1-target/cur)*50;else tb=(1-cur/target)*50;$("cropL").value=$("cropR").value=lr.toFixed(1);$("cropT").value=$("cropB").value=tb.toFixed(1);$("cropL").dispatchEvent(new Event("input"));};
$("gifAlpha").oninput=()=>{$("gifAlphaL").textContent=$("gifAlpha").value;updateEstimate();};
$("gifSpeed").oninput=()=>{$("gifSpeedL").textContent=$("gifSpeed").value+"%";};
$("gifTransparent").onchange=updateEstimate;
/* ======================= estimate ======================= */
let estTimer = 0, estToken = 0;
function updateEstimate(){
const selN = selectedReady().length;
$("eCount").textContent = items.length ? (selN + " of " + items.length) : "\u2014";
const pc = +$("pngColors").value||0;
$("eFmt").textContent = fmtLabel(outFmt) + (outFmt==="image/png" ? (pc>0 ? " \u00b7 " + pc + "c" : " \u00b7 24-bit") : "");
$("exportBtn").disabled = exporting || selN === 0;
const it = items[sel];
if(!it || !it.bitmap){ $("eDims").textContent = "\u2014"; $("eBytes").textContent = "\u2014"; return; }
const G = outputGeom(it.bitmap);
$("eDims").textContent = G.w + "\u00d7" + G.h;
clearTimeout(estTimer);
const token = ++estToken;
estTimer = setTimeout(async () => {
try{
const cur = items[sel];
const source=cur&&(cur.bitmap||(cur.frames&&cur.frames[0]));
if(!source){ $("eBytes").textContent = "\u2014"; return; }
if(outFmt === "image/gif" && cur.frames && cur.frames.length > 1){if(token === estToken) $("eBytes").textContent = "calculated on export";return;}
const blob = await encodeCanvas(renderToCanvas(source), false);
if(token !== estToken) return;
$("eBytes").textContent = blob ? human(blob.size) : "\u2014";
}catch(e){ if(token === estToken) $("eBytes").textContent = "\u2014"; }
}, 300);
}
/* ======================= encoding ======================= */
function canvasToBlob(cv, mime, q){ return new Promise(res => cv.toBlob(res, mime, q)); }
async function encodeCanvas(cv, doTarget){
if(outFmt === "application/pdf") return makePdf([cv]);
if(outFmt === "image/gif") return encodeStillGif(cv);
if(outFmt === "image/png"){
const colors = +$("pngColors").value || 0;
if(colors > 0) return encodeIndexedPNG(cv, colors, $("pngDither").checked);
return encodeLosslessPNG(cv); // adaptive-filtered 24/32-bit (Photoshop PNG-24 style)
}
const q = (+$("quality").value||82)/100;
if(doTarget && $("targetOn").checked){
const unit = +$("targetUnit").value, limit = (+$("targetSize").value||2) * unit;
return encodeToTarget(cv, limit);
}
return canvasToBlob(cv, outFmt, q);
}
async function encodeToTarget(cv, limit){
let lo = 0.05, hi = 0.98, best = null;
let blob = await canvasToBlob(cv, outFmt, hi);
if(blob && blob.size <= limit) return blob;
for(let i = 0; i < 8; i++){
const mid = (lo + hi) / 2;
blob = await canvasToBlob(cv, outFmt, mid);
if(!blob){ break; }
if(blob.size <= limit){ best = blob; lo = mid; } else { hi = mid; }
}
return best || await canvasToBlob(cv, outFmt, lo);
}
/* ---------- PNG plumbing (CRC, chunks, zlib, adaptive filtering) ---------- */
async function deflateZlib(u8){
if(typeof CompressionStream === "undefined") return null;
const cs = new CompressionStream("deflate"); // zlib wrapper (RFC1950) — what PNG needs
const w = cs.writable.getWriter(); w.write(u8); w.close();
const buf = await new Response(cs.readable).arrayBuffer();
return new Uint8Array(buf);
}
const _crcTable = (() => { const t = new Uint32Array(256);
for(let n=0;n<256;n++){ let c=n; for(let k=0;k<8;k++) c = c&1 ? 0xEDB88320^(c>>>1) : c>>>1; t[n]=c>>>0; } return t; })();
function crc32(buf){ let c=0xFFFFFFFF; for(let i=0;i<buf.length;i++) c=_crcTable[(c^buf[i])&255]^(c>>>8); return (c^0xFFFFFFFF)>>>0; }
function u32be(n){ return new Uint8Array([(n>>>24)&255,(n>>>16)&255,(n>>>8)&255,n&255]); }
function pngChunk(type, data){
const t = new Uint8Array(4); for(let i=0;i<4;i++) t[i]=type.charCodeAt(i);
const body = new Uint8Array(t.length + data.length); body.set(t,0); body.set(data,t.length);
const out = new Uint8Array(4 + body.length + 4);
out.set(u32be(data.length),0); out.set(body,4); out.set(u32be(crc32(body)), 4+body.length);
return out;
}
function paeth(a,b,c){ const p=a+b-c, pa=Math.abs(p-a), pb=Math.abs(p-b), pc=Math.abs(p-c);
return pa<=pb && pa<=pc ? a : pb<=pc ? b : c; }
/* adaptive per-scanline filtering (None/Sub/Up/Average/Paeth), min-sum-of-abs heuristic.
Works for any bytes-per-pixel: 1 (indexed), 3 (RGB), 4 (RGBA). This is the core of
Photoshop-grade lossless PNG compression — no colour is changed, files just get much smaller. */
function filterScanlines(data, w, h, bpp){
const stride = w*bpp;
const out = new Uint8Array(h*(stride+1));
const c0=new Uint8Array(stride), c1=new Uint8Array(stride), c2=new Uint8Array(stride), c3=new Uint8Array(stride), c4=new Uint8Array(stride);
let prev = new Uint8Array(stride);
for(let y=0;y<h;y++){
const row = data.subarray(y*stride, y*stride+stride);
c0.set(row);
for(let i=0;i<stride;i++){
const a = i>=bpp ? row[i-bpp] : 0, b = prev[i], c = i>=bpp ? prev[i-bpp] : 0;
c1[i] = (row[i]-a) & 255;
c2[i] = (row[i]-b) & 255;
c3[i] = (row[i]-((a+b)>>1)) & 255;
c4[i] = (row[i]-paeth(a,b,c)) & 255;
}
let bestF=0, bestScore=Infinity;
const cands=[c0,c1,c2,c3,c4];
for(let f=0;f<5;f++){ let s=0; const cc=cands[f]; for(let i=0;i<stride;i++){ const v=cc[i]; s += v<128 ? v : 256-v; } if(s<bestScore){ bestScore=s; bestF=f; } }
out[y*(stride+1)] = bestF;
out.set(cands[bestF], y*(stride+1)+1);
prev = row.slice ? row.slice() : new Uint8Array(row); // keep a stable copy for the next row
}
return out;
}
function assemblePNG(w, h, colorType, chunksBetween, idat){
const sig = new Uint8Array([137,80,78,71,13,10,26,10]);
const ihdr = new Uint8Array(13);
ihdr.set(u32be(w),0); ihdr.set(u32be(h),4); ihdr[8]=8; ihdr[9]=colorType; ihdr[10]=0; ihdr[11]=0; ihdr[12]=0;
const chunks = [ sig, pngChunk("IHDR",ihdr) ];
for(const c of (chunksBetween||[])) chunks.push(c);
chunks.push(pngChunk("IDAT", idat));
chunks.push(pngChunk("IEND", new Uint8Array(0)));
let total=0; chunks.forEach(c=>total+=c.length);
const out=new Uint8Array(total); let off=0; chunks.forEach(c=>{ out.set(c,off); off+=c.length; });
return new Blob([out], { type:"image/png" });
}
/* Lossless 24/32-bit PNG. Detects alpha; RGB (type 2) if fully opaque, else RGBA (type 6). */
async function encodeLosslessPNG(cv){
const ctx = cv.getContext("2d");
const { data, width:w, height:h } = ctx.getImageData(0,0,cv.width,cv.height);
let hasAlpha = false;
for(let i=3;i<data.length;i+=4){ if(data[i] !== 255){ hasAlpha = true; break; } }
let pixels, bpp, colorType;
if(hasAlpha){ pixels = new Uint8Array(data.buffer.slice(0)); bpp = 4; colorType = 6; }
else {
bpp = 3; colorType = 2;
pixels = new Uint8Array(w*h*3);
for(let p=0,q=0;q<w*h;q++,p+=4){ pixels[q*3]=data[p]; pixels[q*3+1]=data[p+1]; pixels[q*3+2]=data[p+2]; }
}
const filtered = filterScanlines(pixels, w, h, bpp);
const idat = await deflateZlib(filtered);
if(!idat) return canvasToBlob(cv, "image/png"); // no CompressionStream → browser PNG
return assemblePNG(w, h, colorType, null, idat);
}
/* ---------- indexed PNG (median cut + adaptive filtering) ---------- */
const _hist = new Int32Array(32768), _rs = new Int32Array(32768), _gs = new Int32Array(32768), _bs = new Int32Array(32768);
const _binArr = new Int32Array(32768);
function buildPalette(data, maxColors){
_hist.fill(0); _rs.fill(0); _gs.fill(0); _bs.fill(0);
for(let i=0;i<data.length;i+=4){
const r=data[i],g=data[i+1],b=data[i+2];
const k=((r>>3)<<10)|((g>>3)<<5)|(b>>3);
_hist[k]++; _rs[k]+=r; _gs[k]+=g; _bs[k]+=b;
}
let m=0; for(let k=0;k<32768;k++) if(_hist[k]) _binArr[m++]=k;
const stat=(s,e)=>{
let rmin=31,rmax=0,gmin=31,gmax=0,bmin=31,bmax=0;
for(let i=s;i<e;i++){ const k=_binArr[i], r=(k>>10)&31,g=(k>>5)&31,b=k&31;
if(r<rmin)rmin=r; if(r>rmax)rmax=r; if(g<gmin)gmin=g; if(g>gmax)gmax=g; if(b<bmin)bmin=b; if(b>bmax)bmax=b; }
const dr=rmax-rmin,dg=gmax-gmin,db=bmax-bmin; let chan=0,ext=dr;
if(dg>ext){chan=1;ext=dg;} if(db>ext){chan=2;ext=db;}
return {s,e,chan,ext};
};
let boxes=[stat(0,m)];
while(boxes.length<maxColors){
let bi=-1,best=0;
for(let i=0;i<boxes.length;i++){ const B=boxes[i]; if(B.e-B.s<2) continue; if(B.ext>best){best=B.ext;bi=i;} }
if(bi<0) break;
const B=boxes[bi], shift=B.chan===0?10:B.chan===1?5:0;
const sub=Array.from(_binArr.subarray(B.s,B.e));
sub.sort((x,y)=>(((x>>shift)&31)-((y>>shift)&31)));
_binArr.set(sub,B.s);
let total=0; for(let i=B.s;i<B.e;i++) total+=_hist[_binArr[i]];
let acc=0,mid=B.s+1;
for(let i=B.s;i<B.e;i++){ acc+=_hist[_binArr[i]]; if(acc*2>=total){ mid=i+1; break; } }
if(mid<=B.s) mid=B.s+1; if(mid>=B.e) mid=B.e-1;
boxes.splice(bi,1,stat(B.s,mid),stat(mid,B.e));
}
const pal=new Uint8Array(768); let count=0;
for(let i=0;i<boxes.length;i++){
const B=boxes[i]; let c=0,R=0,G=0,Bl=0;
for(let x=B.s;x<B.e;x++){ const k=_binArr[x]; c+=_hist[k]; R+=_rs[k]; G+=_gs[k]; Bl+=_bs[k]; }
if(c){ pal[i*3]=Math.round(R/c); pal[i*3+1]=Math.round(G/c); pal[i*3+2]=Math.round(Bl/c); count++; }
}
return { pal, count: Math.max(1,count) };
}
const _near = new Int16Array(32768);
function mapToPalette(data, w, h, pal, palCount, dither){
const idx=new Uint8Array(w*h); _near.fill(-1);
const nearest=(r,g,b)=>{
const key=((r>>3)<<10)|((g>>3)<<5)|(b>>3); const hit=_near[key]; if(hit>=0) return hit;
let bd=Infinity,bi=0;
for(let i=0;i<palCount;i++){ const dr=r-pal[i*3],dg=g-pal[i*3+1],db=b-pal[i*3+2]; const d=dr*dr*3+dg*dg*6+db*db; if(d<bd){bd=d;bi=i;} }
_near[key]=bi; return bi;
};
if(!dither){ for(let p=0,q=0;q<idx.length;q++,p+=4) idx[q]=nearest(data[p],data[p+1],data[p+2]); return idx; }
const buf=new Float32Array(w*h*3);
for(let p=0,q=0;q<w*h;q++,p+=4){ buf[q*3]=data[p]; buf[q*3+1]=data[p+1]; buf[q*3+2]=data[p+2]; }
const cl=v=>v<0?0:(v>255?255:v);
for(let y=0;y<h;y++) for(let x=0;x<w;x++){
const q=y*w+x,o=q*3; const r=cl(buf[o]),g=cl(buf[o+1]),b=cl(buf[o+2]);
const i=nearest(r|0,g|0,b|0); idx[q]=i;
const er=(r-pal[i*3])*0.75,eg=(g-pal[i*3+1])*0.75,eb=(b-pal[i*3+2])*0.75;
if(x+1<w){ const oo=(q+1)*3; buf[oo]+=er*0.4375; buf[oo+1]+=eg*0.4375; buf[oo+2]+=eb*0.4375; }
if(y+1<h){
if(x>0){ const oo=(q+w-1)*3; buf[oo]+=er*0.1875; buf[oo+1]+=eg*0.1875; buf[oo+2]+=eb*0.1875; }
{ const oo=(q+w)*3; buf[oo]+=er*0.3125; buf[oo+1]+=eg*0.3125; buf[oo+2]+=eb*0.3125; }
if(x+1<w){ const oo=(q+w+1)*3; buf[oo]+=er*0.0625; buf[oo+1]+=eg*0.0625; buf[oo+2]+=eb*0.0625; }
}
}
return idx;
}
async function encodeIndexedPNG(cv, colors, dither){
const ctx = cv.getContext("2d");
const { data, width:w, height:h } = ctx.getImageData(0,0,cv.width,cv.height);
const { pal, count } = buildPalette(data, colors);
const idx = mapToPalette(data, w, h, pal, count, dither);
const filtered = filterScanlines(idx, w, h, 1); // adaptive filtering on indices too
const idat = await deflateZlib(filtered);
if(!idat) return canvasToBlob(cv, "image/png");
const plte = pngChunk("PLTE", pal.subarray(0, count*3));
return assemblePNG(w, h, 3, [plte], idat);
}
/* ---------- compact animated GIF encoder: fixed 216-colour palette ---------- */
function gifBytes(it){const a=[];return{a,u8(v){a.push(v&255)},u16(v){a.push(v&255,(v>>8)&255)},str(t){for(const c of t)a.push(c.charCodeAt(0))},arr(v){for(const x of v)a.push(x)}}}
function gifPalette(){const p=[];for(let r=0;r<6;r++)for(let g=0;g<6;g++)for(let b=0;b<6;b++)p.push(r*51,g*51,b*51);while(p.length<768)p.push(0);return p;}
function gifIndex(data){const o=new Uint8Array(data.length/4),keep=$("gifTransparent").checked,cut=+$("gifAlpha").value||128;for(let p=0,q=0;q<o.length;q++,p+=4){if(keep&&data[p+3]<cut){o[q]=255;continue;}const r=Math.round(data[p]/51),g=Math.round(data[p+1]/51),b=Math.round(data[p+2]/51);o[q]=r*36+g*6+b;}return o;}
function lzwGif(idx,min=8){const clear=1<<min,eoi=clear+1;let size=min+1,next=eoi+1,dict=new Map(),bits=0,nb=0,out=[];const put=c=>{bits|=c<<nb;nb+=size;while(nb>=8){out.push(bits&255);bits>>=8;nb-=8;}};const reset=()=>{dict=new Map();size=min+1;next=eoi+1;};put(clear);let pref=idx[0]||0;for(let i=1;i<idx.length;i++){const k=pref+','+idx[i];if(dict.has(k))pref=dict.get(k);else{put(pref);if(next<4096){dict.set(k,next++);if(next===(1<<size)&&size<12)size++;}else{put(clear);reset();}pref=idx[i];}}put(pref);put(eoi);if(nb)out.push(bits&255);return out;}
function addGifFrame(w,indices,delay,W,H){w.u8(0x21);w.u8(0xF9);w.u8(4);w.u8($("gifTransparent").checked?9:4); /* disposal 2 + transparency, or disposal 1 */w.u16(Math.max(2,Math.min(65535,Math.round(delay/10))));w.u8($("gifTransparent").checked?255:0);w.u8(0);w.u8(0x2C);w.u16(0);w.u16(0);w.u16(W);w.u16(H);w.u8(0);w.u8(8);const z=lzwGif(indices);for(let i=0;i<z.length;i+=255){const n=Math.min(255,z.length-i);w.u8(n);w.arr(z.slice(i,i+n));}w.u8(0);}
async function encodeGifCanvases(canvases,delays,loop){
if(!canvases.length)throw new Error("GIF has no frames");const W=canvases[0].width,H=canvases[0].height;
const w=gifBytes();w.str("GIF89a");w.u16(W);w.u16(H);w.u8(0xF7);w.u8(0);w.u8(0);w.arr(gifPalette());
if(loop){w.u8(0x21);w.u8(0xFF);w.u8(11);w.str("NETSCAPE2.0");w.u8(3);w.u8(1);w.u16(0);w.u8(0);}
for(let i=0;i<canvases.length;i++){const cv=canvases[i];if(cv.width!==W||cv.height!==H)throw new Error("GIF frame size mismatch");const d=cv.getContext("2d",{willReadFrequently:true}).getImageData(0,0,W,H).data;addGifFrame(w,gifIndex(d),delays[i]||100,W,H);if(exporting){$("barI").style.width=Math.min(95,5+(i+1)/canvases.length*88)+"%";say($("status"),"Encoding GIF frame "+(i+1)+" of "+canvases.length+"…");}if(i%2===0)await wait(0);if(cancel)throw new Error("Export stopped");}
w.u8(0x3B);const blob=new Blob([new Uint8Array(w.a)],{type:"image/gif"});if(blob.size<20)throw new Error("GIF encoder produced an empty file");return blob;
}
async function encodeStillGif(cv){return encodeGifCanvases([cv],[100],false);}
async function encodeAnimatedItem(it){if(!it.frames||!it.frames.length)throw new Error("No animated GIF frames were decoded");const arr=[];for(let i=0;i<it.frames.length;i++){const src=renderToCanvas(it.frames[i]),c=document.createElement("canvas");c.width=src.width;c.height=src.height;c.getContext("2d").drawImage(src,0,0);arr.push(c);if(i%6===0)await wait(0);}const sp=(+$("gifSpeed").value||100)/100;return encodeGifCanvases(arr,(it.delays||[]).map(d=>d/sp),$("gifLoop").checked);}
/* ---------- PDF: one page per image, JPEG embedded (DCTDecode) ---------- */
async function makePdf(canvases){
const q = clamp((+$("quality").value||82)/100, 0.4, 0.95);
const bytes = [];
const push = s => { for(let i=0;i<s.length;i++) bytes.push(s.charCodeAt(i) & 255); };
const pushBytes = arr => { for(let i=0;i<arr.length;i++) bytes.push(arr[i]); };
const imgDatas = [];
for(const cv of canvases){ const b = await canvasToBlob(cv, "image/jpeg", q); imgDatas.push(new Uint8Array(await b.arrayBuffer())); }
const N = canvases.length;
const offsets = [];
const start = () => offsets.push(bytes.length);
push("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
start(); push("1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
const kids = []; for(let i=0;i<N;i++) kids.push((3 + i*3) + " 0 R");
start(); push("2 0 obj\n<< /Type /Pages /Count " + N + " /Kids [ " + kids.join(" ") + " ] >>\nendobj\n");
for(let i=0;i<N;i++){
const cv = canvases[i], w = cv.width, h = cv.height;
/* A PDF unit is 1/72 inch, so using raw pixels made a 4000px photo into a
55-inch page. Scale each page to fill A4 in its own orientation. */
const sc = Math.min(595 / Math.min(w,h), 842 / Math.max(w,h));
const pw = (w*sc).toFixed(2), ph = (h*sc).toFixed(2);
const pageObj = 3 + i*3, contentObj = pageObj + 1, imgObj = pageObj + 2;
start();
push(pageObj + " 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " + pw + " " + ph + "] " +
"/Resources << /XObject << /Im0 " + imgObj + " 0 R >> >> /Contents " + contentObj + " 0 R >>\nendobj\n");
const content = "q\n" + pw + " 0 0 " + ph + " 0 0 cm\n/Im0 Do\nQ\n";
start();
push(contentObj + " 0 obj\n<< /Length " + content.length + " >>\nstream\n" + content + "endstream\nendobj\n");
const data = imgDatas[i];
start();
push(imgObj + " 0 obj\n<< /Type /XObject /Subtype /Image /Width " + w + " /Height " + h +
" /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length " + data.length + " >>\nstream\n");
pushBytes(data);
push("\nendstream\nendobj\n");
}
const xrefPos = bytes.length, total = 2 + N*3;
push("xref\n0 " + (total+1) + "\n");
push("0000000000 65535 f \n");
for(const off of offsets){ push(String(off).padStart(10,"0") + " 00000 n \n"); }
push("trailer\n<< /Size " + (total+1) + " /Root 1 0 R >>\nstartxref\n" + xrefPos + "\n%%EOF");
return new Blob([new Uint8Array(bytes)], { type: "application/pdf" });
}
/* ======================= naming ======================= */
function outNameFor(it, i, w, h){
const mode = document.querySelector("#nameMode button.on").dataset.m;
const ext = extFor(outFmt);
const num = (+$("startN").value||1) + i;
if(mode === "keep") return safeName(baseName(it.name), "image") + "." + ext;
const tpl = ($("tpl").value || "IMG_{n}")
.replace(/\{n\}/g, String(num).padStart(3,"0"))
.replace(/\{name\}/g, baseName(it.name))
.replace(/\{date\}/g, todayStr())
.replace(/\{w\}/g, w).replace(/\{h\}/g, h);
return safeName(($("prefix").value||"") + tpl + ($("suffix").value||""), "image") + "." + ext;
}
/* Two source files can easily produce the same output name (e.g. "Keep original"
with IMG_001.heic from two different folders). Without this, the second silently
overwrites the first when saving to a picked folder. */
function uniqueName(name, used){
if(!used.has(name)){ used.add(name); return name; }
const dot = name.lastIndexOf(".");
const stem = dot > 0 ? name.slice(0, dot) : name;
const ext = dot > 0 ? name.slice(dot) : "";
let k = 2, next;
do { next = stem + "-" + k + ext; k++; } while(used.has(next));
used.add(next); return next;
}
/* ======================= save helpers ======================= */
function download(blob, name){
const a = document.createElement("a");
a.href = URL.createObjectURL(blob); a.download = name; a.style.display = "none";
document.body.appendChild(a); a.click();
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 12000);
}
/* ======================= export ======================= */
$("stopBtn").addEventListener("click", () => { cancel = true; say($("status"), "Stopping\u2026"); });
$("exportBtn").addEventListener("click", async () => {
if(exporting) return;
const ready = selectedReady();
if(!ready.length){ say($("status"), "Tick at least one readable image first.", "err"); return; }
if(outFmt === "image/avif" && support["image/avif"] === false){
say($("status"), "This browser can\u2019t encode AVIF. Pick WebP or JPEG, or use Chrome/Edge.", "err"); return;
}
if(outFmt === "application/pdf") return exportPdf(ready);
exporting = true; cancel = false; lock(true);
$("bar").style.display = "block"; $("barI").style.width = "0%";
say($("status"), "Converting\u2026");
let dirHandle = null;
if(ready.length > 1 && window.showDirectoryPicker){
try{ dirHandle = await window.showDirectoryPicker({ id:"pocket-img", mode:"readwrite", startIn:"pictures" }); }
catch(e){ if(e && e.name === "AbortError"){ exporting=false; lock(false); $("bar").style.display="none"; say($("status"),"Export cancelled \u2014 no folder chosen."); return; } dirHandle = null; }
}
let done = 0, failed = 0, i = 0;
const usedNames = new Set();
for(const it of ready){
if(cancel) break;
it.status = "working"; render();
try{
const source=it.bitmap||(it.frames&&it.frames[0]);if(!source)throw new Error("No readable image frame");
const cv = renderToCanvas(source);
const blob = (outFmt==="image/gif" && it.frames && it.frames.length>1) ? await encodeAnimatedItem(it) : await encodeCanvas(cv, true);
if(!blob || !blob.size) throw new Error("empty output");
const name = uniqueName(outNameFor(it, i, cv.width, cv.height), usedNames);
it.outName = name; it.outSize = blob.size;
if(dirHandle){
const fh = await dirHandle.getFileHandle(name, { create: true });
const ws = await fh.createWritable(); await ws.write(blob); await ws.close();
}else{
download(blob, name);
if(ready.length > 1) await wait(300);
}
it.status = "done"; done++;
}catch(e){ it.status = "ready"; it.err = e.message || "convert failed"; failed++; say($("status"), "Could not save "+it.name+": "+it.err, "err"); }
i++;
$("barI").style.width = ((done+failed)/ready.length*100).toFixed(1) + "%";
render();
await wait(0);
}
exporting = false; lock(false); render();
$("stopBtn").style.display = "none"; $("bar").style.display = "none";
const where = dirHandle ? " to \u201c" + dirHandle.name + "\u201d" : (ready.length>1 ? " to your Downloads folder" : "");
say($("status"), cancel ? ("Stopped \u2014 " + done + " saved.") :
("Done \u2014 " + done + " saved" + where + (failed ? " \u00b7 " + failed + " failed" : "") + "."), failed ? "err" : "ok");
});
async function exportPdf(ready){
exporting = true; cancel = false; lock(true);
$("bar").style.display = "block"; $("barI").style.width = "0%";
say($("status"), "Building PDF\u2026");
try{
const canvases = [];
for(let k=0;k<ready.length;k++){
if(cancel) break;
const src = ready[k].bitmap || (ready[k].frames && ready[k].frames[0]);
if(!src) continue;
const cv = renderToCanvas(src);
const c2 = document.createElement("canvas"); c2.width = cv.width; c2.height = cv.height;
c2.getContext("2d").drawImage(cv, 0, 0);
canvases.push(c2);
$("barI").style.width = ((k+1)/ready.length*80).toFixed(1) + "%";
say($("status"), "Rendering page " + (k+1) + " of " + ready.length + "\u2026");
await wait(0);
}
if(cancel){ say($("status"), "Stopped."); }
else{
$("barI").style.width = "92%";
const blob = await makePdf(canvases);
const name = safeName(($("prefix").value||"") + "images_" + todayStr(), "images") + ".pdf";
download(blob, name);
ready.forEach(it => { it.status = "done"; it.outSize = Math.round(blob.size/ready.length); });
say($("status"), "Saved " + name + " (" + human(blob.size) + ", " + ready.length + " page" + (ready.length===1?"":"s") + ").", "ok");
}
}catch(e){ say($("status"), e.message || "PDF failed.", "err"); }
finally{ exporting = false; lock(false); $("stopBtn").style.display = "none"; $("bar").style.display = "none"; render(); }
}
function lock(on){
$("exportBtn").disabled = on;
$("stopBtn").style.display = on ? "block" : "none";
["clearAll","clearDone","pickFiles","pickFolder","selAll","selNone"].forEach(id => $(id).disabled = on);
}
/* don't lose a batch to an accidental tab close */
window.addEventListener("beforeunload", e => { if(exporting){ e.preventDefault(); e.returnValue = ""; } });
/* ======================= keyboard ======================= */
document.addEventListener("keydown", e => {
const tag = (e.target.tagName||"").toLowerCase();
if(tag === "input" || tag === "select" || tag === "textarea" || tag === "button" || tag === "a") return;
if(e.target.isContentEditable) return;
if(e.metaKey || e.ctrlKey || e.altKey) return;
if(exporting) return;
if(e.key === "ArrowLeft"){ e.preventDefault(); if(sel > 0){ sel--; previewFrame = 0; drawPreview(); render(); } }
else if(e.key === "ArrowRight"){ e.preventDefault(); if(sel < items.length-1){ sel++; previewFrame = 0; drawPreview(); render(); } }
else if(e.key === " "){ e.preventDefault(); const it=items[sel]; if(it && it.status!=="error"){ it.selected=!it.selected; render(); } }
else if(e.key === "r" || e.key === "R"){ e.preventDefault(); rot = (rot+90)%360; drawPreview(); updateEstimate(); }
else if(e.key === "Delete" || e.key === "Backspace"){ if(sel>=0){ e.preventDefault(); removeAt(sel); } }
});
/* ======================= startup ======================= */
(async function init(){
support["image/webp"] = await supportsMime("image/webp");
support["image/avif"] = await supportsMime("image/avif");
if(!support["image/avif"]){
const b = document.querySelector('#fmtSeg button[data-fmt="image/avif"]');
if(b){ b.disabled = true; b.title = "Not supported by this browser"; b.style.opacity = ".4"; b.style.cursor = "not-allowed"; }
}
syncFmtUI();
renderTextLayerList();loadLayerToUI();
drawPreview(); render();
})();
})();
</script>
</body>
</html>
|