-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSTITCHING_updated_EJ_LH_LS.jsx
1024 lines (853 loc) · 38.4 KB
/
STITCHING_updated_EJ_LH_LS.jsx
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
////////////// ABOUT THIS SCRIPT /////////////////
// This script has been put together by M. Touillon-Ricci based on J.J. Taylor's Compositor and Finaliser scripts.
// It has been developed to run on Mac OS X. To have it run on a Windows computer, just change the filepath, as Mac and PC directory structures do differ.
// It has been adapted by E. Jiménez to add rotated copies of the left and right hand sides of the photos.
// It has been adapted by L. Happel to also work with fewer images of the fragment.
// It has been adapted by L. Sáenz to add the log of the Hilprecht Sammlung and add more metadata.
////////////// SCRIPT'S STEPS /////////////////
// Sort and gather images into sub-folders named by tablet number.
// Go through each folder and stitch the images together.
// Rescale the image based on the digital color scale.
// Replace the color scale with a digital grey scale.
// Save As TIFF in //BLM-FIS-01/UR/TABLETS/images/2_image assembly area/d_finalised images
// Save As JPEG in //BLM-FIS-01/UR/TABLETS/images/2_image assembly area/d_finalised images/_c_final JPEG at check point
////////////// PREREQUISITES /////////////////
// The digital color scale has to be added at preprocessing stage. The script indeed uses the blue bottom left square of the scale to rescale the whole image.
// If the scale is larger than the object, make sure to crop the scale sensibly, i.e. preserving the original proportions in the cropped version and the blue bottom left square.
// This script uses calculations based on both color and grey scales dimensions. The 5 cm color scale should be 1346 x 462 px. The 5 cm grey scale should be 1346 x 308 px.
// Install the script in your version of Photoshop to access it directly via the application.
// Original location of preprocessed files: //BLM-FIS-01/UR/TABLETS/images/2_image assembly area/a_preprocessed images in need of stitching
////////////// RUN PHOTOSHOP AND LAUNCH SCRIPT /////////////////
// For Photoshop CS2 and higher only.
// Enable double-clicking from Mac Finder or Windows Explorer and bring application forward.
// Global variables at the start of script
// Global variables at the start of script
// Global variables at the start of script
var folderinlocalcomputer; // Declare globally but don't assign yet
// Define the color setting function
function setColorFromSettings(settings) {
var color = new SolidColor();
// Use a default of black if settings are undefined
var useWhite = settings && settings.backgroundColor === "white";
color.rgb.red = useWhite ? 255 : 0;
color.rgb.green = useWhite ? 255 : 0;
color.rgb.blue = useWhite ? 255 : 0;
return color;
}
//target photoshop
app.bringToFront();
// Move the color initialization to the main function where we have settings
function main() {
// Show settings dialog first
var settingsResult = showSettingsDialog();
if (!settingsResult) return; // Exit if cancelled
// Now we can safely set the colors based on settings
var backgroundColor = setColorFromSettings(settingsResult.settings);
app.foregroundColor = backgroundColor;
app.backgroundColor = backgroundColor;
var topFolder = settingsResult.topFolder;
if (!topFolder.exists) {
alert("Source folder no longer exists. Please check settings.");
return;
}}
function getSettingsFilePath() {
var userData = Folder.userData;
var settingsFolder = new Folder(userData + "/TabletScript");
if (!settingsFolder.exists) {
settingsFolder.create();
}
return settingsFolder + "/tablet_script_settings.txt";
}
// Function to read settings from a file
function readSettings() {
var settingsFile = new File(getSettingsFilePath());
if (settingsFile.exists) {
settingsFile.open('r');
var content = settingsFile.read();
settingsFile.close();
var parts = content.split("|||");
if (parts.length >= 11) { // Updated to expect at least 11 parts
return {
photographer: parts[0],
institution: parts[1],
copyrightnotice: parts[2],
xmpUsageTerms: parts[3],
sourcePath: parts[4],
outputPath: parts[5],
addLogo: parts[6] === "true",
logoPath: parts[7] || "",
dpi: parseInt(parts[8]) || 600,
compression: parts[9] || "none",
creditLine: parts[10] || "Funding for photography...",
backgroundColor: parts[11] || "black" // Add this line
};
}
}
return null;
}
// Function to get all settings
function getAllSettings() {
var settings = readSettings() || {};
return {
photographer: settings.photographer || "",
institution: settings.institution || "",
copyrightnotice: settings.copyrightnotice || "",
xmpUsageTerms: settings.xmpUsageTerms || "",
sourcePath: settings.sourcePath || "",
outputPath: settings.outputPath || "",
addLogo: settings.addLogo || false,
logoPath: settings.logoPath || "",
dpi: settings.dpi || 600,
backgroundColor: settings.backgroundColor || "black" // Add this line
};
}
// Function to save all settings
function saveAllSettings(settings) {
var settingsFile = new File(getSettingsFilePath());
settingsFile.open('w');
settingsFile.write([
settings.photographer,
settings.institution,
settings.copyrightnotice,
settings.xmpUsageTerms,
settings.sourcePath,
settings.outputPath,
settings.addLogo,
settings.logoPath,
settings.dpi,
settings.compression,
settings.creditLine,
settings.backgroundColor // Add this line
].join("|||"));
settingsFile.close();
}
// Function to show settings dialog
function showSettingsDialog() {
var settings = getAllSettings();
var dialog = new Window("dialog", "Script Settings");
dialog.orientation = "column";
dialog.alignChildren = "fill";
// Create tab panel
var tpanel = dialog.add("tabbedpanel");
var mainTab = tpanel.add("tab", undefined, "Main Settings");
var iptcTab = tpanel.add("tab", undefined, "IPTC Metadata");
// Main Tab
mainTab.alignChildren = "fill";
// Photographer
var photographerGroup = mainTab.add("group");
photographerGroup.add("statictext", undefined, "Photographer:");
var photographerInput = photographerGroup.add("edittext", undefined, settings.photographer);
photographerInput.preferredSize.width = 300;
// Institution
var institutionGroup = mainTab.add("group");
institutionGroup.add("statictext", undefined, "Institution:");
var institutionInput = institutionGroup.add("edittext", undefined, settings.institution);
institutionInput.preferredSize.width = 300;
// Copyright Notice
var copyrightGroup = mainTab.add("group");
copyrightGroup.add("statictext", undefined, "Copyright Notice:");
var copyrightInput = copyrightGroup.add("edittext", undefined, settings.copyrightnotice);
copyrightInput.preferredSize.width = 300;
// XMP Copyright
var usageTermsGroup = mainTab.add("group");
usageTermsGroup.add("statictext", undefined, "Copyright (Usage Terms):");
var usageTermsInput = usageTermsGroup.add("edittext", undefined, settings.xmpUsageTerms);
usageTermsInput.preferredSize.width = 300;
// Source Folder
var sourceGroup = mainTab.add("group");
sourceGroup.add("statictext", undefined, "Source Folder:");
var sourceInput = sourceGroup.add("edittext", undefined, settings.sourcePath);
sourceInput.preferredSize.width = 250;
var sourceBrowse = sourceGroup.add("button", undefined, "Browse");
// Output Folder
var outputGroup = mainTab.add("group");
outputGroup.add("statictext", undefined, "Output Folder:");
var outputInput = outputGroup.add("edittext", undefined, settings.outputPath);
outputInput.preferredSize.width = 250;
var outputBrowse = outputGroup.add("button", undefined, "Browse");
// Logo Options
var logoGroup = mainTab.add("group");
var addLogoCheckbox = logoGroup.add("checkbox", undefined, "Add Logo to Images");
addLogoCheckbox.value = settings.addLogo;
var logoPathGroup = mainTab.add("group");
logoPathGroup.add("statictext", undefined, "Logo File:");
var logoPathInput = logoPathGroup.add("edittext", undefined, settings.logoPath);
logoPathInput.preferredSize.width = 250;
var logoPathBrowse = logoPathGroup.add("button", undefined, "Browse");
// Enable/disable logo path controls based on checkbox
logoPathInput.enabled = addLogoCheckbox.value;
logoPathBrowse.enabled = addLogoCheckbox.value;
// Add DPI Selection Group (new)
var dpiGroup = mainTab.add("group");
dpiGroup.add("statictext", undefined, "Final resolution for the stitched image:");
var dpiRadioGroup = dpiGroup.add("group");
var dpi300Radio = dpiRadioGroup.add("radiobutton", undefined, "300 DPI");
var dpi600Radio = dpiRadioGroup.add("radiobutton", undefined, "600 DPI");
// Set initial DPI radio selection based on saved settings
if (settings.dpi === 300) {
dpi300Radio.value = true;
} else {
dpi600Radio.value = true;
}
var backgroundColorGroup = mainTab.add("group");
backgroundColorGroup.add("statictext", undefined, "Background Color:");
var backgroundColorRadio = backgroundColorGroup.add("group");
var blackRadio = backgroundColorRadio.add("radiobutton", undefined, "Black");
var whiteRadio = backgroundColorRadio.add("radiobutton", undefined, "White");
// Set initial background color selection based on saved settings
if (settings.backgroundColor === "white") {
whiteRadio.value = true;
} else {
blackRadio.value = true;
}
// Add TIFF Compression selection (new)
var compressionGroup = mainTab.add("group");
compressionGroup.add("statictext", undefined, "TIFF Compression:");
var compressionDropdown = compressionGroup.add("dropdownlist", undefined, ["None", "LZW", "ZIP"]);
compressionDropdown.selection = 0; // Default to None
// Set initial compression selection based on saved settings
switch(settings.compression) {
case "lzw":
compressionDropdown.selection = 1;
break;
case "zip":
compressionDropdown.selection = 2;
break;
default:
compressionDropdown.selection = 0;
}
// IPTC Tab
iptcTab.alignChildren = "fill";
var iptcPanel = iptcTab.add("panel", undefined, "IPTC Metadata Fields");
iptcPanel.orientation = "column";
iptcPanel.alignChildren = "left";
iptcPanel.margins = [10, 15, 10, 10];
// Title
var titleGroup = iptcPanel.add("group");
titleGroup.add("statictext", undefined, "Title:");
var titleDisplay = titleGroup.add("statictext", undefined, "(Will be set to Tablet Number)");
titleDisplay.preferredSize.width = 300;
// Headline
var headlineGroup = iptcPanel.add("group");
headlineGroup.add("statictext", undefined, "Headline:");
var headlineDisplay = headlineGroup.add("statictext", undefined, "(Will be set to Tablet Number)");
headlineDisplay.preferredSize.width = 300;
// Author/Creator
var authorGroup = iptcPanel.add("group");
authorGroup.add("statictext", undefined, "Author/Creator:");
var authorDisplay = authorGroup.add("statictext", undefined, settings.photographer);
authorDisplay.preferredSize.width = 300;
// Credit Line (Editable)
var creditGroup = iptcPanel.add("group");
creditGroup.add("statictext", undefined, "Credit Line:");
var creditInput = creditGroup.add("edittext", undefined,
"Funding for photography and post-processing provided by a Sofja Kovalevskaja Award " +
"(Alexander von Humboldt Foundation, German Federal Ministry for Education and Research) " +
"as part of the Electronic Babylonian Literature-Projekt of the Ludwig-Maximilians-Universität München",
{multiline: true});
creditInput.preferredSize.width = 300;
creditInput.preferredSize.height = 100;
// Copyright Notice
var copyrightNoticeGroup = iptcPanel.add("group");
copyrightNoticeGroup.add("statictext", undefined, "Copyright Notice:");
var copyrightNoticeDisplay = copyrightNoticeGroup.add("statictext", undefined, settings.copyrightnotice);
copyrightNoticeDisplay.preferredSize.width = 300;
// Copyright Status
var copyrightStatusGroup = iptcPanel.add("group");
copyrightStatusGroup.add("statictext", undefined, "Copyright Status:");
var copyrightStatusDisplay = copyrightStatusGroup.add("statictext", undefined, "Copyrighted Work");
copyrightStatusDisplay.preferredSize.width = 300;
// XMP Copyright
var usageTermsGroup = iptcPanel.add("group");
usageTermsGroup.add("statictext", undefined, "Rights Usage Terms:");
var usageTermsDisplay = usageTermsGroup.add("statictext", undefined, settings.xmpUsageTerms);
usageTermsDisplay.preferredSize.width = 300;
addLogoCheckbox.onClick = function() {
logoPathInput.enabled = addLogoCheckbox.value;
logoPathBrowse.enabled = addLogoCheckbox.value;
}
// Buttons at the bottom of the dialog
var buttonGroup = dialog.add("group");
buttonGroup.alignment = "center";
var okButton = buttonGroup.add("button", undefined, "OK");
var cancelButton = buttonGroup.add("button", undefined, "Cancel");
// Browse button handlers
sourceBrowse.onClick = function() {
var folder = Folder.selectDialog("Select source folder");
if (folder) sourceInput.text = folder.fsName;
}
outputBrowse.onClick = function() {
var folder = Folder.selectDialog("Select output folder");
if (folder) outputInput.text = folder.fsName;
}
logoPathBrowse.onClick = function() {
var file = File.openDialog("Select logo file", "*.png;*.jpg;*.tif;*.psd");
if (file) logoPathInput.text = file.fsName;
}
okButton.onClick = function() {
settings = {
photographer: photographerInput.text,
institution: institutionInput.text,
copyrightnotice: copyrightInput.text,
xmpUsageTerms: usageTermsInput.text,
sourcePath: sourceInput.text,
outputPath: outputInput.text,
addLogo: addLogoCheckbox.value,
logoPath: logoPathInput.text,
dpi: dpi300Radio.value ? 300 : 600,
compression: compressionDropdown.selection ?
compressionDropdown.selection.text.toLowerCase() : "none",
creditLine: creditInput.text,
backgroundColor: blackRadio.value ? "black" : "white"
};
saveAllSettings(settings);
dialog.close(1);
}
cancelButton.onClick = function() {
dialog.close(0);
}
// Force the initial tab to be "Main Settings"
tpanel.selection = mainTab;
var result = dialog.show();
if (result == 1) {
// Update global variables
photographer = settings.photographer;
institution = settings.institution;
copyrightnotice = settings.copyrightnotice;
folderinlocalcomputer = settings.outputPath + "/";
return {
settings: settings,
topFolder: new Folder(settings.sourcePath)
};
}
return null;
}
// Modified main function start
function main() {
// Show settings dialog first
var settingsResult = showSettingsDialog();
if (!settingsResult) return; // Exit if cancelled
var topFolder = settingsResult.topFolder;
if (!topFolder.exists) {
alert("Source folder no longer exists. Please check settings.");
return;
}
// Continue with the rest of your main function...
var images = topFolder.getFiles();
// gives each BM filename
for (var i = 0; i < images.length; i++) {
var image = images[i];
// the point of the if clause is to deal with top level folders that contain a mix of just files dumped in together plus sub-folders containing their images. When the script goes on to stitch images in folders, it will do this both to the folders created here and to those that already exist
if (image instanceof File) {
var newFolderLongName = image.name.toString();
// this line cuts off the file extension .tif and the _NN
var newFolderName = newFolderLongName.slice(0, -7);
var newFolder = Folder(topFolder + "/" + newFolderName);
// Check if it exists already; if not create it.
if(!newFolder.exists) newFolder.create();
// JS has no move for file. Thus copy, and delete original.
var myFile = File(topFolder + "/" + newFolderLongName);
myFile.copy(newFolder + "/" + newFolderLongName);
myFile.remove();
}
}
// get a list of files
var subFolder = topFolder.getFiles();
var images = []
// loop through each to grab the 6 files and stitch them
for (var i = 0; i < subFolder.length; i++) {
images.push(subFolder[i].getFiles());
}
for (var i = 0; i < images.length; i++) {
importFolderAsLayers(images[i], settingsResult); // Pass settingsResult here
}
}
///////////////////////////////////////////////////////////////////////////////
// getFiles - get all files in the target folder
///////////////////////////////////////////////////////////////////////////////
function getFiles(topFolder) {
// declare local variables
var fileArray = new Array();
var extRE = /\.(?:png|gif|jpg|bmp|tif|psd|dng)$/i;
// get all files in source folder
var docs = topFolder.getFiles();
var len = docs.length;
for (var i = 0; i < len; i++) {
var doc = docs[i];
// only match files (not folders)
if (doc instanceof File) {
// store all recognized files into an array
var docName = doc.name;
if (docName.match(extRE)) {
fileArray.push(doc);
}
}
// return file array
return fileArray;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////// COMPOSITING ////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// importFolderAsLayers - imports all files within target folder as layers named according to their filename
function importFolderAsLayers(fileArray, settingsResult) {
// Get DPI from settings
var n = settingsResult.settings.dpi;
// Set Adobe Photoshop CS6 to use pixels and display no dialogs
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.PIXELS;
// Set background color based on settings
var backgroundColor = setColorFromSettings(settingsResult.settings);
app.foregroundColor = backgroundColor;
app.backgroundColor = backgroundColor;
// Create a blank canvas using the selected DPI
var newDoc = documents.add(8000, 8000, n, 'A new final in the making', NewDocumentMode.RGB, DocumentFill.BACKGROUNDCOLOR);
var newLayer = newDoc.activeLayer;
// loop through all files in the source folder
for (var i = 0; i < fileArray.length; i++) {
// open document
var doc = open(fileArray[i]);
// get document name (and remove file extension)
var name = doc.name.replace(/(?:\.[^.]*$|$)/, '');
// convert to RGB; convert to 8-bpc; merge visible
doc.changeMode(ChangeMode.RGB);
doc.bitsPerChannel = BitsPerChannelType.EIGHT;
doc.artLayers.add();
doc.mergeVisibleLayers();
// rename layer; duplicate to new document
var layer = doc.activeLayer;
layer.name = name;
layer.duplicate(newDoc, ElementPlacement.PLACEATBEGINNING);
// close imported document
doc.close(SaveOptions.DONOTSAVECHANGES);
}
// remove unwanted material from names ready for naming of layers and final file
var layerName = app.activeDocument.layers[1].name;
var trimmed = layerName.replace("BMND", "ND");
var tabletNumber = trimmed.slice(0, -3);
var layerPrefix = trimmed.slice(0, -2);
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//add layers if missing
var exist = app.activeDocument.layers.length;
var goal = 7;
var diff = goal - exist;
//add a 10x10 pixel placeholder for every missing side
if (diff > 0){
for (i = 0; i < diff; i++){
var newLayer = app.activeDocument.artLayers.add();
newLayer.name = "EMPTY"
app.activeDocument.selection.select([[0,0], [10, 0], [10,10], [0,10]]);
var fillColor = setColorFromSettings(settingsResult.settings);
app.activeDocument.selection.fill(fillColor);
app.activeDocument.selection.deselect();
}
}
//fix layer order
//disable background layer
var backgroundL = app.activeDocument.backgroundLayer;
backgroundL.isBackgroundLayer = false;
//Search every side view
for (i = 1; i <= 7; i++){
//create list of layers by name, redo every loop, in case order changes
var layers = app.activeDocument.layers
var layersByNames = []
for (j = 0; j < layers.length; j++){
layersByNames.push((layers[j].name))
};
//search list for numbered suffix
var pattern = new RegExp(i + '$');
var containsPattern = false
for (k = 0; k < layersByNames.length; k++){
//searches for i in layername of k
if (pattern.test(layersByNames[k])){
containsPattern = true;
//move side to right index
switch(i){
case 1:
//Obverse to 5
swapLayers(k, 5);
break;
case 2:
//Reverse to 4
swapLayers(k, 4);
break;
case 3:
//Bottom to 3
swapLayers(k, 3);
break;
case 4:
//Upper to 2
swapLayers(k, 2);
break;
case 5:
//Right to 1
swapLayers(k, 1);
break;
case 6:
//Left to 0
swapLayers(k, 0);
break;
}
break;
}
}
}
//enable background layer?
backgroundL.isBackgroundLayer = true;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//this moves the obv to centre
//old: var obvLayerBounds = app.activeDocument.layers[1].bounds
var obvLayerBounds = app.activeDocument.layers[5].bounds;
// get top left position
var obvLayerX = (obvLayerBounds[2].value - obvLayerBounds[0].value);
var obvLayerY = (obvLayerBounds[3].value - obvLayerBounds[1].value);
// the difference between where layer needs to be and is now
var obvDeltaX = (8000-obvLayerX)/2;
// move the layer into position
app.activeDocument.layers[5].translate (obvDeltaX);
//this positions left to left of obv
var leftLayerBounds = app.activeDocument.layers[1].bounds;
var leftLayerX = (leftLayerBounds[2].value - leftLayerBounds[0].value);
var leftLayerY = (leftLayerBounds[3].value - leftLayerBounds[1].value);
var leftDeltaX = obvDeltaX-leftLayerX;
app.activeDocument.layers[1].translate (leftDeltaX);
// resize the left to match obv
//Grab the width
var masterWidth = app.activeDocument.layers[5].bounds[2]-app.activeDocument.layers[5].bounds[0];
//Grab the height
var masterHeight = app.activeDocument.layers[5].bounds[3]-app.activeDocument.layers[5].bounds[1];
//Grab the width
var originalLeftWidth = app.activeDocument.layers[1].bounds[2]-app.activeDocument.layers[1].bounds[0];
//Grab the height
var originalLeftHeight = app.activeDocument.layers[1].bounds[3]-app.activeDocument.layers[1].bounds[1];
// Get % of desired dimension compared to original then apply to both H and W
var newLeftHeight= (masterHeight/originalLeftHeight)*100;
app.activeDocument.layers[1].resize(newLeftHeight,newLeftHeight,AnchorPosition.TOPRIGHT);
//this positions right to right of obv
var rightLayerBounds = app.activeDocument.layers[0].bounds;
var rightLayerX = (rightLayerBounds[2].value - rightLayerBounds[0].value);
var rightDeltaX = obvDeltaX+obvLayerX;
app.activeDocument.layers[0].translate (rightDeltaX);
// resize the right to match obv. See above sub left for comments on stages
var originalRightWidth = app.activeDocument.layers[0].bounds[2]-app.activeDocument.layers[0].bounds[0];
var originalRightHeight = app.activeDocument.layers[0].bounds[3]-app.activeDocument.layers[0].bounds[1];
var newRightHeight= (masterHeight/originalRightHeight)*100;
app.activeDocument.layers[0].resize(newRightHeight,newRightHeight,AnchorPosition.TOPLEFT);
//this positions base to below obv
var baseLayerBounds = app.activeDocument.layers[2].bounds;
var baseLayerX = (baseLayerBounds[2].value - baseLayerBounds[0].value);
var baseLayerY = (baseLayerBounds[3].value - baseLayerBounds[1].value);
var baseDeltaX = (8000-obvLayerX)/2;
var baseDeltaY = (obvLayerY);
app.activeDocument.layers[2].translate (baseDeltaX, baseDeltaY);
// resize the base to match obv. See above sub left for comments on stages
var originalBaseWidth = app.activeDocument.layers[2].bounds[2]-app.activeDocument.layers[2].bounds[0];
var originalBaseHeight = app.activeDocument.layers[2].bounds[3]-app.activeDocument.layers[2].bounds[1];
var newBaseWidth= (masterWidth/originalBaseWidth)*100;
app.activeDocument.layers[2].resize(newBaseWidth,newBaseWidth,AnchorPosition.TOPLEFT);
//this positions rev to below base
var revLayerBounds = app.activeDocument.layers[4].bounds;
var revLayerX = (revLayerBounds[2].value - revLayerBounds[0].value);
var revLayerY = (revLayerBounds[3].value - revLayerBounds[1].value);
var revDeltaX = (8000-obvLayerX)/2;
var newBaseLayerBounds = app.activeDocument.layers[2].bounds;
var newBaseLayerY = (newBaseLayerBounds[3].value - newBaseLayerBounds[1].value);
var revDeltaY = (obvLayerY+newBaseLayerY);
app.activeDocument.layers[4].translate (revDeltaX, revDeltaY);
// resize rev to match obv
var originalRevWidth = app.activeDocument.layers[4].bounds[2]-app.activeDocument.layers[4].bounds[0];
var originalRevHeight = app.activeDocument.layers[4].bounds[3]-app.activeDocument.layers[4].bounds[1];
var newRevWidth= (masterWidth/originalRevWidth)*100;
app.activeDocument.layers[4].resize(newRevWidth,newRevWidth,AnchorPosition.TOPLEFT);
//this positions top to below rev
var topLayerBounds = app.activeDocument.layers[3].bounds;
var topLayerX = (topLayerBounds[2].value - topLayerBounds[0].value);
var topLayerY = (topLayerBounds[3].value - topLayerBounds[1].value);
var newRevLayerBounds = app.activeDocument.layers[4].bounds;
var newRevLayerY = (newRevLayerBounds[3].value - newRevLayerBounds[1].value);
var topDeltaX = (8000-obvLayerX)/2;
var topDeltaY = (obvLayerY+newBaseLayerY+newRevLayerY);
app.activeDocument.layers[3].translate (topDeltaX, topDeltaY);
// resize the top to match obv. See above sub left for comments on stages
var originalTopWidth = app.activeDocument.layers[3].bounds[2]-app.activeDocument.layers[3].bounds[0];
var originalTopHeight = app.activeDocument.layers[3].bounds[3]-app.activeDocument.layers[3].bounds[1];
var newTopWidth= (masterWidth/originalTopWidth)*100;
app.activeDocument.layers[3].resize(newTopWidth,newTopWidth,AnchorPosition.TOPLEFT);
// duplicate, rotate, and position new left layer (new step)
app.activeDocument.layers[1].duplicate();
app.activeDocument.layers[1].rotate(180, AnchorPosition.MIDDLECENTER);
var leftNewLayerBounds = app.activeDocument.layers[1].bounds;
var newRevLayerBounds = app.activeDocument.layers[5].bounds;
var leftNewLayerY = (newRevLayerBounds[3].value - leftNewLayerBounds[3].value);
app.activeDocument.layers[1].translate (0, leftNewLayerY);
// duplicate, rotate, and position new right layer (new step)
app.activeDocument.layers[0].duplicate();
app.activeDocument.layers[0].rotate(180, AnchorPosition.MIDDLECENTER);
var rightNewLayerBounds = app.activeDocument.layers[0].bounds;
var newRevLayerBounds = app.activeDocument.layers[6].bounds;
var rightNewLayerY = (newRevLayerBounds[3].value - rightNewLayerBounds[3].value);
app.activeDocument.layers[0].translate (0, rightNewLayerY);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// trim excess from image
newDoc.resizeCanvas(app.activeDocument.width + 2000, app.activeDocument.height + 5000, AnchorPosition.TOPCENTER);
// Set the background color to black (explicitly)
var backgroundColor = setColorFromSettings(settingsResult.settings);
app.backgroundColor = backgroundColor;
// Resize the canvas
var newCanvasHeight = app.activeDocument.height + 5000; // Adjust height as needed
var newCanvasWidth = app.activeDocument.width;
app.activeDocument.resizeCanvas(newCanvasWidth, newCanvasHeight, AnchorPosition.TOPCENTER);
// Ensure the newly added area is filled with black
var newAreaStartY = app.activeDocument.height - 5000; // Calculate starting point of the new area
app.activeDocument.selection.select([
[0, newAreaStartY],
[newCanvasWidth, newAreaStartY],
[newCanvasWidth, app.activeDocument.height],
[0, app.activeDocument.height]
]);
var fillColor = setColorFromSettings(settingsResult.settings);
app.activeDocument.selection.fill(fillColor);
app.activeDocument.selection.deselect();
newDoc.revealAll(DocumentFill.BACKGROUNDCOLOR);
newDoc.trim(TrimType.TOPLEFT, true, true, true, true);
// flatten layers
app.activeDocument.flatten()
// reset ruler to cm
app.preferences.rulerUnits = Units.CM
// save final file
function SaveTIFF(saveFile){
tiffSaveOptions = new TiffSaveOptions();
tiffSaveOptions.embedColorProfile = true;
tiffSaveOptions.layers = true;
//tiffSaveOptions.imageCompression = TIFFEncodingLZW
activeDocument.saveAs(saveFile, tiffSaveOptions, true, Extension.LOWERCASE);
}
///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// RESCALING /////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
function selectBlue(){ //using eyedropper in Color Range selector. Get this using the Script Listener
var id2382 = charIDToTypeID( "ClrR" );
var desc488 = new ActionDescriptor();
var id2383 = charIDToTypeID( "Fzns" );
desc488.putInteger( id2383, 40 );
var id2384 = charIDToTypeID( "Mnm " );
var desc489 = new ActionDescriptor();
var id2385 = charIDToTypeID( "Lmnc" );
desc489.putDouble( id2385, 13.910000 );
var id2386 = charIDToTypeID( "A " );
desc489.putDouble( id2386, 44.920000 );
var id2387 = charIDToTypeID( "B " );
desc489.putDouble( id2387, -73.620000 );
var id2388 = charIDToTypeID( "LbCl" );
desc488.putObject( id2384, id2388, desc489 );
var id2389 = charIDToTypeID( "Mxm " );
var desc490 = new ActionDescriptor();
var id2390 = charIDToTypeID( "Lmnc" );
desc490.putDouble( id2390, 13.910000 );
var id2391 = charIDToTypeID( "A " );
desc490.putDouble( id2391, 44.920000 );
var id2392 = charIDToTypeID( "B " );
desc490.putDouble( id2392, -73.620000 );
var id2393 = charIDToTypeID( "LbCl" );
desc488.putObject( id2389, id2393, desc490 );
executeAction( id2382, desc488, DialogModes.NO );
}
function getSelectionBounds (doc) { //alternative to using bounds function
var l = srcDoc.artLayers.add();
srcDoc.selection.fill(app.foregroundColor);
var bnds = l.bounds;
var hs = srcDoc.historyStates;
if (hs[hs.length-2].name == "Layer Order") {
srcDoc.activeHistoryState = hs[hs.length-4];
} else {
srcDoc.activeHistoryState = hs[hs.length-3];
}
for (var i = 0; i < bnds.length; i++) {
bnds[i] = bnds[i].value;
}
return bnds;
};
//script work starts
var strtRulerUnits = app.preferences.rulerUnits;
if (strtRulerUnits != Units.CM)
{
app.preferences.rulerUnits = Units.CM;
}
//source document
var srcDoc = activeDocument;
//Use the same DPI value for rescaling
selectBlue();
var BlueSquare = getSelectionBounds();
var horizBlue = BlueSquare[2] - BlueSquare[0];
var vertBlue = BlueSquare[3] - BlueSquare[1];
if ((horizBlue / vertBlue) > 1) // it really is around 1.33; then 5cm scale
{
var c = (0.77/horizBlue); // For 5cm scale - target size of 0.77cm
}
else // ((horizBlue / vertBlue) < 1) // it really is around 1; then 2cm scale
{
var c = (0.3/horizBlue); // For 2cm scale - target size of 0.3cm
}
//resize image using proper DPI conversion
srcDoc.resizeImage(null,null,n,ResampleMethod.BICUBIC);
var scale = (c * srcDoc.width*n/2.54);//new size of image in pixels - 2.54 to convert dpi into pixels/cm
srcDoc.resizeImage(UnitValue(scale,"px"),null,null,ResampleMethod.BICUBIC);
// flatten layers
app.activeDocument.flatten();
// add wrap around margin of 100 px
app.preferences.rulerUnits = Units.PIXELS;
app.activeDocument.trim(TrimType.TOPLEFT, true, true, true, true);
srcDoc.resizeCanvas(app.activeDocument.width+200, app.activeDocument.height+200, AnchorPosition.MIDDLECENTER);
app.preferences.rulerUnits = Units.CM;
//delete all guides if there are guides
function deleteAllGuides() {
var idDlt = charIDToTypeID( "Dlt " );
var desc1129 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref268 = new ActionReference();
var idGd = charIDToTypeID( "Gd " );
var idOrdn = charIDToTypeID( "Ordn" );
var idAl = charIDToTypeID( "Al " );
ref268.putEnumerated( idGd, idOrdn, idAl );
desc1129.putReference( idnull, ref268 );
executeAction( idDlt, desc1129, DialogModes.NO );
}
// Access the active document
var docRef = app.activeDocument;
// Access the document info object
var info = docRef.info;
// Set IPTC Core metadata
info.title = tabletNumber; // Title (Überschrift)
info.credit = settingsResult.settings.creditLine;
info.copyrightNotice = settingsResult.settings.copyrightnotice; // Copyright Notice
info.copyrighted = CopyrightedType.COPYRIGHTEDWORK; // Copyright Status
info.headline = tabletNumber; // Headline or Title
info.author = photographer; // Author/Creator
// Save changes to metadata
docRef.info = info;
if (ExternalObject.AdobeXMPScript == null) {
ExternalObject.AdobeXMPScript = new ExternalObject("lib:AdobeXMPScript");
}
var xmpMetadata = new XMPMeta(docRef.xmpMetadata.rawData);
xmpMetadata.setLocalizedText(
XMPConst.NS_XMP_RIGHTS,
"xmpRights:UsageTerms",
null, // Default language
"x-default", // Language code
settingsResult.settings.xmpUsageTerms // The text from the main tab
);
// Save the updated metadata back to the document
docRef.xmpMetadata.rawData = xmpMetadata.serialize();
//run function
deleteAllGuides()
// function to swap layer with placeholder layer in hierarchy
function swapLayers(index1, index2){
var doc = app.activeDocument;
var layer1 = doc.layers[index1];
var layer2 = doc.layers[index2];
if (index1 < index2) {
layer1.move(layer2, ElementPlacement.PLACEBEFORE);
layer2.move(doc.layers[index1], ElementPlacement.PLACEBEFORE);
} else {
layer2.move(layer1, ElementPlacement.PLACEBEFORE);
layer1.move(doc.layers[index2], ElementPlacement.PLACEBEFORE);
}
}
// Ask user if they want to add a logo
// Add logo if it was selected in settings
if (settingsResult.settings.addLogo && settingsResult.settings.logoPath) {
var logoFile = new File(settingsResult.settings.logoPath);
if (logoFile.exists) {
// Open the active document (base image)
var baseDoc = app.activeDocument;
// Open the logo
var logoDoc = app.open(logoFile);
// Get the logo's original dimensions before duplicating
var originalLogoWidth = logoDoc.width;
// Duplicate the logo into the base image
var logoLayer = logoDoc.artLayers[0].duplicate(baseDoc, ElementPlacement.PLACEATEND);
// Close the logo document
logoDoc.close(SaveOptions.DONOTSAVECHANGES);
// Back to the base image document
app.activeDocument = baseDoc;
// Get dimensions
var baseWidth = baseDoc.width;
var baseHeight = baseDoc.height;
app.activeDocument.activeLayer = logoLayer; // Ensure the correct layer is active
var logoBounds = logoLayer.bounds;
var logoWidth = logoBounds[2] - logoBounds[0]; // Right - Left
var logoHeight = logoBounds[3] - logoBounds[1]; // Bottom - Top
// Check if logo needs resizing
if (logoWidth > baseWidth) {
// Calculate resize percentage (70% of original if wider than base image)
var resizePercentage = 70;
logoLayer.resize(resizePercentage, resizePercentage, AnchorPosition.MIDDLECENTER);
// Update logo dimensions after resize
logoBounds = logoLayer.bounds;
logoWidth = logoBounds[2] - logoBounds[0];
logoHeight = logoBounds[3] - logoBounds[1];
}
// Calculate new canvas height
var newCanvasHeight = baseHeight + logoHeight;
// Expand the canvas
baseDoc.resizeCanvas(baseWidth, newCanvasHeight, AnchorPosition.TOPCENTER);
// Create a temporary layer for black fill
var fillLayer = baseDoc.artLayers.add();
fillLayer.name = "Black Fill";
fillLayer.move(baseDoc, ElementPlacement.PLACEATEND);
// Select the new canvas area
baseDoc.selection.select([
[0, baseHeight],
[baseWidth, baseHeight],
[baseWidth, newCanvasHeight],
[0, newCanvasHeight]
]);
// Fill the selected area with black
var fillColor = setColorFromSettings(settingsResult.settings);
baseDoc.selection.fill(fillColor);
baseDoc.selection.deselect();
// Merge the fill layer down
fillLayer.merge();
// Move the logo to the very bottom and center it horizontally
var xOffset = (baseWidth - (logoBounds[2] - logoBounds[0])) / 2 - logoBounds[0]; // Center horizontally
var yOffset = baseHeight - logoBounds[1]; // Distance to move the logo vertically
logoLayer.translate(xOffset, yOffset);
// Merge all layers to finalize
baseDoc.flatten();
}
}
//saveAs(saveIn, options, asCopy, extensionType)
saveFinal = new File(folderinlocalcomputer + tabletNumber + ".tif");
var tiffSaveOptions = new TiffSaveOptions();
tiffSaveOptions.embedColorProfile = true;
tiffSaveOptions.layers = true;
// Set compression based on settings
switch(settingsResult.settings.compression) {
case "lzw":
tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW;
break;
case "zip":
tiffSaveOptions.imageCompression = TIFFEncoding.TIFFZIP;
break;
default:
tiffSaveOptions.imageCompression = TIFFEncoding.NONE;
}