-
Notifications
You must be signed in to change notification settings - Fork 7
/
file.c
3009 lines (2507 loc) · 101 KB
/
file.c
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
/* Panorama_Tools - Generate, Edit and Convert Panoramic Images
Copyright (C) 1998,1999 - Helmut Dersch [email protected]
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this software; see the file COPYING. If not, a copy
can be downloaded from http://www.gnu.org/licenses/gpl.html, or
obtained by writing to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
/*------------------------------------------------------------*/
// Functions to read and write Photoshop, and write tiffs
// Updated by Jim Watters 2003 Nov 21
// Every layer of a multi layer PSD file should have a shape mask.
// The shape mask defines the shape of the image from the background.
// 3 problems with PTSTitcher
// - The Seam options for middle(s0 'blend')and edge(s1 'paste') are ignored by PTStitcher
// - Both the PSD options of "With_Mask" and "Without_Mask" both create mask except:
// - the "With_Mask" puts the seam in the center and uses the feathering to blend
// - the "Without_Mask" puts the seam at the edge and ignores the feathering, does no blending
// - 16bit input images are reduced to 8bit and not able to create 16bit psd files.
// For backward compatability reasons continue to create mask for "WithOut_Mask"
// When creating multi image PSD files try to create shape mask (Alpha) and clip mask properly
// Updated writePSDwithLayer and addLayer to create both proper shape mask and clip mask
// As a hack to check to see if a shape mask can be created from the alpha channel do a check for feathering in the Alpha channel
// If Alpha channel has feathering create a new shape mask
// Add two new functions hasFeather and writeTransparentAlpha
// Enabled 16bit multilayer PSD files; except they still are 8bit; They are already converted in PTStitcher
// Updated by Jim Watters 2003 Nov 24
// fixed bug with odd data size for psd files
// There is only one pad char at the end of all layer and channel data, if everything is a odd length
// Update by Jim Watters 2003 Dec 29
// Also fix ReadPSD to handle multilayers
// Update by Rik Littlefield 2004 June 29
// Fix getImageRectangle to not pagefault so badly.
// Dynamically allocate scanline buffer in writeWhiteBackground,
// to avoid buffer overflow and crash on large images.
// Fix 16bit Radial Shift and Adjust - Kevin & Jim 2004 July
// 2006 Max Lyons - Various modifications
#include <assert.h>
#include <time.h>
#include "filter.h"
#include "file.h"
#include "pttiff.h"
#include "metadata.h"
#include "sys_compat.h"
// local functions
static int writeImageDataPlanar ( Image *im, file_spec fnum );
static int readImageDataPlanar (Image *im, file_spec fnum ) ;
static int ParsePSDHeader ( char *header, Image *im, Boolean *pbBig );
static int writeChannelData ( Image *im, file_spec fnum, int channel, PTRect *r );
static int writeLayerAndMask ( Image *im, file_spec fnum, Boolean bBig );
static void getImageRectangle ( Image *im, PTRect *r );
static int fileCopy ( file_spec src, file_spec dest, size_t numBytes, unsigned char *buf);
static void orAlpha ( unsigned char* alpha, unsigned char *buf, Image *im, PTRect *r );
static void writeWhiteBackground ( uint32_t width, uint32_t height, file_spec fnum, Boolean bBig );
static int addLayer ( Image *im, file_spec src, file_spec fnum , stBuf *sB, Boolean bBig );
static int hasFeather ( Image *im );
static int writeTransparentAlpha ( Image *im, file_spec fnum, PTRect *theRect );
char *psdBlendingModesNames[] = {
"Normal",
"Color",
"Darken",
"Difference",
"Dissolve",
"Hard Light",
"Hue",
"Lighten",
"Luminosity",
"Multiply",
"Overlay",
"Sof Light",
"Saturation",
"Screen"
};
char *psdBlendingModesInternalName[] = {
"norm",
"colr",
"dark",
"diff",
"diss",
"hLit",
"hue",
"lite",
"lum",
"mul",
"over",
"sLit",
"sat",
"scrn"
};
#define PSDHLENGTH 26
size_t panoPSDResourceWrite(file_spec fnum, uint16_t resource, int32_t len, size_t dataLen, char *resourceData)
{
//struct _ColorModeDataBlock
//{
// BYTE Type[4]; /* Always "8BIM" */
// WORD ID; /* (See table below) */
// BYTE Name[]; /* Even-length Pascal-format string, 2 bytes or longer */
// LONG Size; /* Length of resource data following, in bytes */
// BYTE Data[]; /* Resource data, padded to even length */
//};
//
size_t startLocation = ftell(fnum);
panoWriteUCHAR( fnum, '8' );
panoWriteUCHAR( fnum, 'B' );
panoWriteUCHAR( fnum, 'I' );
panoWriteUCHAR( fnum, 'M' );
panoWriteSHORT( fnum, resource);
panoWriteSHORT( fnum, 0); // Null string 2 bytes (length)
panoWriteINT32( fnum, len); //size of the record (4 bytes)
if (dataLen > 0 && resourceData != NULL) {
mywrite( fnum, dataLen, resourceData );
if( (ftell(fnum) - startLocation)%2 )
{
panoWriteUCHAR( fnum, 0 );
}
}
return ftell(fnum) - startLocation;
}
size_t panoPSDPICTResourceWrite(file_spec fnum, unsigned char resource, unsigned char record, size_t len, char *recordData)
{
// See IPTC Information Intercharge Model Exchange Version 4.
size_t startLocation = ftell(fnum);
panoWriteUCHAR( fnum, 0x1c );
panoWriteUCHAR( fnum, resource );
panoWriteUCHAR( fnum, record );
panoWriteSHORT( fnum, (short)len ); //length
if (len !=0 && recordData != NULL ) {
mywrite( fnum, len, recordData);
}
return ftell(fnum) - startLocation;
}
#define CREATED_BY_PSD "Panotools " PTVERSIONBIT " " VERSION
#define IPTC_VERSION_ID 0
#define IPTC_DATE_CREATED_ID 0x37
#define IPTC_TIME_CREATED_ID 0x3C
#define IPTC_ORIGINATING_PROGRAM_ID 0x41
#define IPTC_BY_LINE_ID 0x50
#define IPTC_COPYRIGHTNOTICE_ID 0x74
#define IPTC_CAPTION_ABSTRACT_ID 0x78
#define IPTC_DESCRIPTION_WRITER_ID 0x7a
size_t panoPSDResourcesBlockWrite(Image *im, file_spec fnum)
{
size_t saveLocation = 0;
size_t saveLocationForSize=0;
// This function is a bit cryptic mainly because PSD forces the lenght to be known before a record is written.
// What I have decided is to make the writing process non-sequential.
// Write an empty length first, then "rewind" and write its real
// one. It will make things way easier and more maintainable.
// Write 4 bytes
saveLocationForSize = ftell(fnum);
panoWriteINT32( fnum, 1234 ); // Image Resources size
if (im->metadata.iccProfile.size > 0) {
// Currently we only include ICC profile if it exists
// We need to write an image Resources block
// Write Image resources header
// Write ICC Profile block
panoPSDResourceWrite(fnum, 0x040f, im->metadata.iccProfile.size,
im->metadata.iccProfile.size, im->metadata.iccProfile.data);
}
{
// we will refactor this chunck
size_t startLocationPICT = 0;
size_t saveLocationPICT = 0;
size_t descLength = 0;
char IPTCVersion[3];
// To write PICT we need to create a resource of type IPCT
// Inside it write the sequence of PICT records
// It is easy to add new records
// The computation of the length of the subrecords is automatic
// The collection of IPTC records is padded with a single character if the length is odd
// save the location so we can rewind later and write the correct value
saveLocationPICT = ftell(fnum);
// Write an empty length first, then "rewind" and write its real
// one. It will make things way easier and more maintainable.
panoPSDResourceWrite(fnum, 0x0404, 0000, 0, NULL);
startLocationPICT = ftell(fnum);
IPTCVersion[0] = 0;
IPTCVersion[1] = 2;
IPTCVersion[2] = 0;
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_VERSION_ID, 2, IPTCVersion);
// Must not exceed 32 char by IPTC standard.
descLength = (short)min( 32, strlen(CREATED_BY_PSD) );
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_DESCRIPTION_WRITER_ID, descLength, CREATED_BY_PSD );
if(im->metadata.imageDescription)
{
// caption abstract: 0x78 "script... (2000 bytes max)
// Must not exceed 2000 char by IPTC standard.
descLength = (short)min( 2000, strlen(im->metadata.imageDescription) );
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_CAPTION_ABSTRACT_ID, descLength, im->metadata.imageDescription );
}
if(im->metadata.artist)
{
// By-line: 0x50 "John Smith"
// Must not exceed 32 char by IPTC standard.
descLength = (short)min( 32, strlen(im->metadata.artist) );
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_BY_LINE_ID, descLength, im->metadata.artist );
}
if(im->metadata.copyright)
{
//Copyright: 0x74 "(c) John Smith, 2011"
// Must not exceed 128 char by IPTC standard.
descLength = (short)min( 128, strlen(im->metadata.copyright) );
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_COPYRIGHTNOTICE_ID, descLength, im->metadata.copyright );
}
if(TRUE)
{
char *name;
name = panoBasenameOfExecutable();
//Originating Program: 0x41 "PTtiff2PSD"
// Must not exceed 32 char by IPTC standard.
descLength = (short)min( 32, strlen(name) );
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_ORIGINATING_PROGRAM_ID, descLength, name );
}
// date time will be the current date time the image was created
if(FALSE)//im->metadata.datetime)
{
char sDate[20];
char sTime[20];
time_t t;
struct tm *currentTime;
// get the local time,
t = time(NULL);
currentTime = localtime(&t);
//date: 0x37 "YYYYMMDD"
if (strftime(sDate, sizeof(sDate), "%Y%m%d", currentTime) != 0) {
// Must not exceed 8 char by IPTC standard.
assert(strlen(sDate)== 8); // Just making sure
descLength = (short)min( 8, strlen(sDate) );
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_DATE_CREATED_ID, descLength, sDate );
}
else
PrintError("Error converting local time in PSD creation");
//Time: 0x3c "HHMMSS±HHMM"
// First get the time
if (panoTimeToStrWithTimeZone(sTime, sizeof(sTime), currentTime)) {
assert(strlen(sTime)==11); // it should always be 11
descLength = (short)min( 11, strlen(sTime) );
panoPSDPICTResourceWrite(fnum, 0x02, IPTC_TIME_CREATED_ID, descLength, sTime );
} else
PrintError("Error converting local time in PSD creation");
}
// Check for odd size resource rec
if( (ftell(fnum) - saveLocationPICT) %2 )
{
// The section is of an odd size pad with a single character
panoWriteUCHAR( fnum, 0 );
}
// Write length
saveLocation = ftell(fnum);
fseek(fnum, saveLocationPICT, SEEK_SET);
assert(saveLocation > saveLocationForSize);
panoPSDResourceWrite(fnum, 0x0404, saveLocation-startLocationPICT, 0, NULL);
fseek(fnum, saveLocation, SEEK_SET);
}
// Write length
saveLocation = ftell(fnum);
fseek(fnum, saveLocationForSize, SEEK_SET);
assert(saveLocation > saveLocationForSize);
panoWriteINT32( fnum, saveLocation - saveLocationForSize-4 ); // Image Resources size
fseek(fnum, saveLocation, SEEK_SET);
return ftell(fnum) - saveLocationForSize;
}
int writePSD ( Image *im, fullPath* fname )
{
return writePS(im, fname, FALSE);
}
// Save image as the background, as a PSD or PSB file
// Image is background, there are no layers
int writePS(Image *im, fullPath *sfile, Boolean bBig )
{
file_spec fnum;
int channels;
int BitsPerChannel;
// Check to see if we need to create PSB instead of PSD file
if(panoImageFullHeight(im) > 30000 || panoImageFullWidth(im) > 30000)
bBig = TRUE;
GetChannels( im, channels );
GetBitsPerChannel( im, BitsPerChannel );
if( myopen( sfile, write_bin, fnum ) )
{
PrintError("Error Writing Image File");
return -1;
}
// Write PSD and PSB Header
// WRITEINT32( '8BPS' );
panoWriteUCHAR( fnum, '8' );
panoWriteUCHAR( fnum, 'B' );
panoWriteUCHAR( fnum, 'P' );
panoWriteUCHAR( fnum, 'S' );
panoWriteSHORT( fnum, bBig? 2 : 1 ); // PSD file must be 1, PSB files must be 2
panoWriteINT32( fnum, 0 ); panoWriteSHORT( fnum, 0 ); // 6 bytes zeroed
panoWriteSHORT( fnum, channels ); // Num of channels
// The Photoshop file has the dimensions of the full size image, regardless
// of whether the TIFF file is "cropped" or not.
// Layers of a PSD file can have the data constrained to only the cropped area, but that is not what we are doing here.
// PSD file is limited to 30000 in width and height, PSB are limited to 300000 in width and height
panoWriteINT32( fnum, panoImageHeight(im) ); // Rows
panoWriteINT32( fnum, panoImageWidth(im) ); // Columns
panoWriteSHORT( fnum, BitsPerChannel ); // BitsPerChannel
switch( im->dataformat ) // Color mode
{
case _Lab: panoWriteSHORT( fnum, 9 );
break;
case _RGB: panoWriteSHORT( fnum, 3 );
break;
default: panoWriteSHORT( fnum, 3 );
}
panoWriteINT32( fnum, 0 ); // Color Mode block
panoPSDResourcesBlockWrite( im, fnum ); // PSD Resource
panoWriteINT32or64( fnum, 0, bBig ); // Layer & Mask
writeImageDataPlanar( im, fnum ); // Image data
myclose (fnum );
return 0;
}
int writePSDwithLayer ( Image *im, fullPath *fname)
{
return writePSwithLayer( im, fname, FALSE);
}
// Save image as single layer PSD or PSB file
// Image is layer in front of white background
int writePSwithLayer(Image *im, fullPath *sfile, Boolean bBig )
{
file_spec fnum;
int BitsPerChannel;
// Check to see if we need to create PSB instead of PSD file
if(panoImageFullHeight(im) > 30000 || panoImageFullWidth(im) > 30000)
bBig = TRUE;
// Jim Watters 2003/11/18: Photoshop CS does 16bit channels if 16 bit in, allow 16 bit out
// TwoToOneByte( im ); // Multilayer image format doesn't support 16 bit channels
GetBitsPerChannel( im, BitsPerChannel );
if( myopen( sfile, write_bin, fnum ) )
{
PrintError("Error Writing Image File");
return -1;
}
// Write PSD and PSB Header
// panoWriteINT32( fnum, '8BPS' );
panoWriteUCHAR( fnum, '8' );
panoWriteUCHAR( fnum, 'B' );
panoWriteUCHAR( fnum, 'P' );
panoWriteUCHAR( fnum, 'S' );
panoWriteSHORT( fnum, bBig? 2 : 1 ); // PSD file must be 1, PSB files must be 2
panoWriteINT32( fnum, 0 ); panoWriteSHORT( fnum, 0 ); // 6 bytes zeroed
panoWriteSHORT( fnum, 3 ); // No of channels; Background always white, 3 channels
//The Photoshop file has the dimensions of the full size image, regardless
//of whether the TIFF file is "cropped" or not.
// PSD file is limited to 30000 in width and height, PSB are limited to 300000 in width and height
panoWriteINT32( fnum, panoImageFullHeight(im) ); // Rows
panoWriteINT32( fnum, panoImageFullWidth(im) ); // Columns
panoWriteSHORT( fnum, BitsPerChannel ); // BitsPerChannel
switch( im->dataformat )
{
case _Lab: panoWriteSHORT( fnum, 9 );
break;
case _RGB: panoWriteSHORT( fnum, 3 );
break;
default: panoWriteSHORT( fnum, 3 );
}
panoWriteINT32( fnum, 0 ); // Color Mode
panoPSDResourcesBlockWrite(im, fnum);
writeLayerAndMask( im, fnum, bBig );
writeWhiteBackground( panoImageFullWidth(im) * (BitsPerChannel/8), panoImageFullHeight(im), fnum, bBig );
myclose (fnum );
return 0;
}
// Add image as additional layer into PSD-file (exported function)
int addLayerToFile( Image *im, fullPath* sfile, fullPath* dfile, stBuf *sB)
{
file_spec src;
file_spec fnum;
Image sim; // background image
char header[128], *h;
size_t count, i, srcCount = 0;
uint32_t len;
unsigned char **buf;
int BitsPerChannel, result = 0;
Boolean bBig = FALSE;
// Jim Watters 2003/11/18: Photoshop CS does 16bit channels if 16 bit in, allow 16 bit out
// TwoToOneByte( im ); // Multilayer image format doesn't support 16 bit channels
GetBitsPerChannel( im, BitsPerChannel );
if( myopen( sfile,read_bin, src ) )
{
PrintError("Error Opening Image File");
return -1;
}
// Read psd header
h = header;
count = PSDHLENGTH;
myread( src,count,h); srcCount += count;
if( count != PSDHLENGTH )
{
PrintError("Error Reading Image File");
myclose( src );
return -1;
}
if( ParsePSDHeader( header, &sim, &bBig ) != 0 )
{
PrintError("addLayerToFile: Wrong File Format");
myclose( src );
return -1;
}
// Check if image can be inserted
// printf("Image size %d %d im %d %d\n", sim.width, sim.height, panoImageWidth(im), panoImageHeight(im));
if( sim.width != panoImageFullWidth(im) || sim.height != panoImageFullHeight(im) )
{
PrintError("Can't add layer: Images have different size");
return -1;
}
// Read (and ignore) Color mode data
panoReadINT32( src, &len );
srcCount += (4 + len);
count = 1;
for( i=0; i<len; i++ )
{
myread(src,count,h);
}
// Read (and ingnore) Image resources
panoReadINT32( src, &len );
srcCount += (4 + len);
count = 1;
for( i=0; i<len; i++ )
{
myread(src,count,h);
}
myclose( src );
if( myopen( sfile, read_bin, src ) )
{
PrintError("Error Opening Image File");
return -1;
}
if( myopen( dfile, write_bin, fnum ) )
{
PrintError("Error Opening Image File");
return -1;
}
// Read and write Fileheader
buf = (unsigned char**)mymalloc( srcCount );
if( buf == NULL )
{
PrintError("Not enough memory");
result = -1;
goto _addLayerToFile_exit;
}
fileCopy( src, fnum, srcCount, *buf );
myfree( (void**)buf );
// Add one layer
if( addLayer( im, src, fnum, sB, bBig ) != 0 )
{
result = -1;
goto _addLayerToFile_exit;
}
writeWhiteBackground( sim.width * (BitsPerChannel/8), sim.height, fnum, bBig );
_addLayerToFile_exit:
myclose( src ); myclose( fnum );
return result;
}
static int writeImageDataPlanar( Image *im, file_spec fnum )
{
register unsigned int x,y,idy, bpp;
unsigned char **channel;
register unsigned char *ch, *idata;
int color;
size_t count;
int BitsPerChannel, channels;
GetBitsPerChannel( im, BitsPerChannel );
GetChannels( im,channels);
printf("Bitx per channel %d channels %d\n", BitsPerChannel, channels);
bpp = im->bitsPerPixel / 8;
// Write Compression info
panoWriteSHORT( fnum, 0 ); // Raw data
// Buffer to hold data in one channel
count = (size_t)im->width * im->height * (BitsPerChannel / 8);
channel = (unsigned char**)mymalloc( count );
if( channel == NULL )
{
PrintError("Not Enough Memory");
return -1;
}
if( BitsPerChannel == 8 )
{
for( color = 0; color<3; color++)
{
ch = *channel; idata = &(*im->data)[color + channels - 3];
for(y=0; y<im->height;y++)
{
idy = y * im->bytesPerLine;
for(x=0; x<im->width;x++)
{
*ch++ = idata [ idy + x * bpp ];
}
}
mywrite( fnum, count, *channel );
}
}
else // 16
{
unsigned short storage;//Kekus 2003 16 bit support
for( color = 0; color<3; color++)
{
ch = *channel; idata = &(*im->data)[2*(color + channels - 3)];
for(y=0; y<im->height;y++)
{
idy = y * im->bytesPerLine;
for(x=0; x<im->width;x++)
{
//Kekus:2003/Nov/18 // JMW 2004 July
storage = *(unsigned short*)&idata [ idy + x * bpp ];
SHORTNUMBER( storage, ch );
//Kekus.
}
}
mywrite( fnum, count, *channel );
}
}
if( im->bitsPerPixel == 32 )
{
// Write 1byte alpha channel
ch = *channel; idata = &(*im->data)[0];
for(y=0; y<im->height;y++)
{
idy = y * im->bytesPerLine;
for(x=0; x<im->width;x++)
{
*ch++ = idata [ idy + x * bpp ];
}
}
mywrite( fnum, count, *channel );
}
else if( im->bitsPerPixel == 64 )
{
// Write 2byte alpha channel
unsigned short storage;
ch = *channel; idata = &(*im->data)[0];
for(y=0; y<im->height;y++)
{
idy = y * im->bytesPerLine;
for(x=0; x<im->width;x++)
{
storage = *(unsigned short*)&idata [ idy + x * bpp ];
SHORTNUMBER( storage, ch );
}
}
mywrite( fnum, count, *channel );
}
myfree( (void**)channel );
return 0;
}
// Write white background, RLE-compressed
static void writeWhiteBackground(uint32_t width, uint32_t height, file_spec fnum, Boolean bBig )
{
uint32_t w8, w;
size_t count;
char *d;
char **scanline;
int numChannels = 3;
int i;
int bytecount;
int dim = height*numChannels;
size_t maxscanline = (width/128)*2 + 2;
scanline = (char**)mymalloc( maxscanline );
if( scanline == NULL )
{
PrintError("Not enough memory");
return;
}
panoWriteSHORT( fnum, 1 ); // RLE compressed
w8 = width;
d = *scanline;
// Set up scanline
for(w=w8; w>128; w-=128)
{
*d++ = -127;
*d++ = 255U;
}
switch(w)
{
case 0: break;
case 1: *d++ = 0;
*d++ = 255U;
break;
default: *d++ = 1-(char)w;
*d++ = 255U;
break;
}
bytecount = (int)(d - *scanline);
// Scanline counts (rows*channels)
for(i=0; i < dim; i++)
{
if(bBig)
{
panoWriteINT32( fnum, bytecount );
}
else
{
panoWriteSHORT( fnum, bytecount );
}
}
// RLE compressed data
count = bytecount;
for(i=0; i < dim; i++)
{
mywrite( fnum, count, *scanline );
}
myfree((void**)scanline);
}
// image is allocated, but not image data
// mode = 0: only load image struct
// mode = 1: also allocate and load data
int readPSD(Image *im, fullPath *sfile, int mode)
{
file_spec src;
char header[128];
char *h;
uint32 len;
uint32 i;
size_t count;
Boolean bBig = FALSE;
if( myopen( sfile, read_bin, src ) )
{
PrintError("Error Opening Image File");
return -1;
}
// Read psd header
h = header;
count = PSDHLENGTH;
myread( src,count,h );
if( count != PSDHLENGTH )
{
PrintError("Error Reading Image File");
myclose( src );
return -1;
}
if( ParsePSDHeader( header, im, &bBig ) != 0 )
{
PrintError("readPSD: Wrong File Format");
myclose( src );
return -1;
}
if( mode == 0 )
{
myclose( src );
return 0;
}
im->data = (unsigned char**) mymalloc( im->dataSize );
if( im->data == NULL )
{
PrintError("Not enough memory to read image");
myclose( src );
return -1;
}
// Read (and ingnore) Color mode data
panoReadINT32( src, &len );
count = 1;
for( i=0; i<len; i++ )
myread(src,count,h);
// Read (and ingnore) Image resources
panoReadINT32( src, &len );
count = 1;
for( i=0; i<len; i++ )
myread(src,count,h);
// Read (and ingnore) Layer mask info
panoReadINT32( src, &len );
count = 1;
for( i=0; i<len; i++ )
myread(src,count,h);
if( readImageDataPlanar( im, src ) != 0 )
{
PrintError("Error reading image");
myclose( src );
return -1;
}
myclose (src );
return 0;
}
static int ParsePSDHeader( char *header, Image *im, Boolean *pbBig )
{
register char *h = header;
short s;
int channels;
if(pbBig == NULL)
{
PrintError( "ParsePSDHeader: Error pbBig is NULL");
return -1;
}
*pbBig = FALSE;
if( *h++ != '8' || *h++ != 'B' || *h++ != 'P' || *h++ != 'S' ||
*h++ != 0 || (*h++ != 1 && *(h-1) != 2 ) ||
*h++ != 0 || *h++ != 0 || *h++ != 0 || *h++ != 0 || *h++ != 0 || *h++ != 0 )
{
PrintError( "ParsePSDHeader: Error reading PSD Header: %c%c%c%c", header[0], header[1], header[2], header[3] );
return -1;
}
if(header[5] == 2)
*pbBig = TRUE;
NUMBERSHORT( s, h );
channels = s;
if( channels < 3 ) //!= 3 && channels != 4 )
{
PrintError( "Number of channels must be 3 or larger" );
return -1;
}
if( channels > 4 ) channels = 4;
NUMBERLONG( im->height, h );
NUMBERLONG( im->width, h );
NUMBERSHORT( s, h );
if( s!= 8 && s!= 16)
{
PrintError( "Depth must be 8 or 16 Bits per Channel" );
return -1;
}
im->bitsPerPixel = s * channels;
NUMBERSHORT( s, h );
switch( s )
{
case 3: im->dataformat = _RGB; break;
case 9: im->dataformat = _Lab; break;
default: PrintError( "Color mode must be RGB or Lab" );return -1;
}
im->bytesPerLine = im->width * (im->bitsPerPixel/8);
im->dataSize = (size_t)im->height * im->bytesPerLine;
return 0;
}
static int readImageDataPlanar(Image *im, file_spec src )
{
register unsigned int x,y,idy, bpp;
unsigned char **channel = NULL;
register unsigned char *h, *idata;
int result = 0, i, chnum,BitsPerChannel, channels;
size_t count;
unsigned short usvar;
GetBitsPerChannel( im, BitsPerChannel );
GetChannels( im, channels );
bpp = im->bitsPerPixel / 8;
// Read Compression info
panoReadSHORT( src, &usvar );
if( usvar!= 0 )
{
PrintError("Image data must not be compressed");
return -1;
}
// Allocate memory for one channel
count = (size_t)im->width * im->height * (BitsPerChannel/8);
channel = (unsigned char**)mymalloc( count );
if( channel == NULL )
{
PrintError("Not Enough Memory");
return -1;
}
for(i = 0; i < channels; i++) // Read each channel
{
chnum = i + channels - 3;
if(chnum == 4) chnum = 0; // Order: r g b (alpha)
myread(src,count,*channel);
if( count != (size_t)im->width * im->height * (BitsPerChannel/8))
{
PrintError("Error Reading Image Data");
result = -1;
goto readImageDataPlanar_exit;
}
h = *channel;
if( BitsPerChannel == 8 )
{
idata = &(*im->data)[chnum];
for(y=0; y<im->height;y++)
{
idy = y * im->bytesPerLine;
for(x=0; x<im->width;x++)
{
idata [ idy + x * bpp ] = *h++;
}
}
}
else // 16
{
idata = &(*im->data)[chnum*2];
for(y=0; y<im->height;y++)
{
idy = y * im->bytesPerLine;
for(x=0; x<im->width;x++)
{
NUMBERSHORT( usvar, h );
*((unsigned short*)&idata [ idy + x * bpp ]) = usvar;
}
}
}
}
readImageDataPlanar_exit:
if( channel != NULL )
myfree( (void**)channel );
return result;
}
// Write image as separate first layer
static int writeLayerAndMask( Image *im, file_spec fnum, Boolean bBig )
{
PTRect theRect;
int64_t lenLayerInfo;
int64_t channelLength;
int i, BitsPerChannel, channels, psdchannels;
int oddSized = 0;
int hasClipMask = 0; // Create a mask
int hasShapeMask = 0; // Create alpha channel
GetBitsPerChannel( im, BitsPerChannel );
GetChannels( im, channels );