/
ImageIO.cpp
1509 lines (1218 loc) · 33 KB
/
ImageIO.cpp
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
// This code is in the public domain -- castanyo@yahoo.es
#include <nvcore/Ptr.h>
#include <nvcore/Containers.h>
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
//#include <nvcore/Tokenizer.h> // @@ Disable temporarily
#include <nvcore/TextWriter.h>
#include <nvmath/Color.h>
#include "ImageIO.h"
#include "Image.h"
#include "FloatImage.h"
#include "TgaFile.h"
#include "PsdFile.h"
// Extern
#if defined(HAVE_JPEG)
extern "C" {
# include <jpeglib.h>
}
#endif
#if defined(HAVE_PNG)
# include <png.h>
#endif
#if defined(HAVE_TIFF)
# define _TIFF_DATA_TYPEDEFS_
# include <tiffio.h>
#endif
#if defined(HAVE_OPENEXR)
# include <ImfIO.h>
# include <ImathBox.h>
# include <ImfChannelList.h>
# include <ImfInputFile.h>
# include <ImfOutputFile.h>
# include <ImfArray.h>
#endif
using namespace nv;
namespace {
// Array of image load plugins.
// static HashMap<String, ImageInput_Plugin> s_plugin_load_map;
// Array of image save plugins.
// static HashMap<String, ImageOutput_Plugin> s_plugin_save_map;
struct Color555 {
uint16 b : 5;
uint16 g : 5;
uint16 r : 5;
};
} // namespace
Image * nv::ImageIO::load(const char * fileName)
{
nvDebugCheck(fileName != NULL);
StdInputStream stream(fileName);
if (stream.isError()) {
return NULL;
}
return ImageIO::load(fileName, stream);
}
Image * nv::ImageIO::load(const char * fileName, Stream & s)
{
nvDebugCheck(fileName != NULL);
nvDebugCheck(s.isLoading());
const char * extension = Path::extension(fileName);
if (strCaseCmp(extension, ".tga") == 0) {
return ImageIO::loadTGA(s);
}
#if defined(HAVE_JPEG)
if (strCaseCmp(extension, ".jpg") == 0 || strCaseCmp(extension, ".jpeg") == 0) {
return loadJPG(s);
}
#endif
#if defined(HAVE_PNG)
if (strCaseCmp(extension, ".png") == 0) {
return loadPNG(s);
}
#endif
if (strCaseCmp(extension, ".psd") == 0) {
return loadPSD(s);
}
// @@ use image plugins?
return NULL;
}
bool nv::ImageIO::save(const char * fileName, Stream & s, Image * img)
{
nvDebugCheck(fileName != NULL);
nvDebugCheck(s.isSaving());
nvDebugCheck(img != NULL);
const char * extension = Path::extension(fileName);
if (strCaseCmp(extension, ".tga") == 0) {
return ImageIO::saveTGA(s, img);
}
return false;
}
bool nv::ImageIO::save(const char * fileName, Image * img)
{
nvDebugCheck(fileName != NULL);
nvDebugCheck(img != NULL);
StdOutputStream stream(fileName);
if (stream.isError())
{
return false;
}
return ImageIO::save(fileName, stream, img);
}
FloatImage * nv::ImageIO::loadFloat(const char * fileName)
{
nvDebugCheck(fileName != NULL);
StdInputStream stream(fileName);
if (stream.isError()) {
return false;
}
return loadFloat(fileName, stream);
}
FloatImage * nv::ImageIO::loadFloat(const char * fileName, Stream & s)
{
nvDebugCheck(fileName != NULL);
const char * extension = Path::extension(fileName);
#if defined(HAVE_TIFF)
if (strCaseCmp(extension, ".tif") == 0 || strCaseCmp(extension, ".tiff") == 0) {
return loadFloatTIFF(fileName, s);
}
#endif
#if defined(HAVE_OPENEXR)
if (strCaseCmp(extension, ".exr") == 0) {
return loadFloatEXR(fileName, s);
}
#endif
/* // @@ Disable temporarily
if (strCaseCmp(extension, ".pfm") == 0) {
return loadFloatPFM(fileName, s);
}
*/
return NULL;
}
bool nv::ImageIO::saveFloat(const char * fileName, const FloatImage * fimage, uint base_component, uint num_components)
{
const char * extension = Path::extension(fileName);
#if defined(HAVE_OPENEXR)
if (strCaseCmp(extension, ".exr") == 0)
{
return ImageIO::saveFloatEXR(fileName, fimage, base_component, num_components);
}
#endif
#if defined(HAVE_TIFF)
if (strCaseCmp(extension, ".tif") == 0 || strCaseCmp(extension, ".tiff") == 0)
{
return ImageIO::saveFloatTIFF(fileName, fimage, base_component, num_components);
}
#endif
/* // @@ Disable Temporarily
if (strCaseCmp(extension, ".pfm") == 0)
{
// return ImageIO::saveFloatPFM(fileName, fimage, base_component, num_components);
}
*/
if (num_components == 3 || num_components == 4)
{
AutoPtr<Image> image(fimage->createImage(base_component, num_components));
nvCheck(image != NULL);
if (num_components == 4)
{
image->setFormat(Image::Format_ARGB);
}
return ImageIO::save(fileName, image.ptr());
}
return false;
}
/// Load TGA image.
Image * nv::ImageIO::loadTGA(Stream & s)
{
nvCheck(!s.isError());
nvCheck(s.isLoading());
TgaHeader tga;
s << tga;
s.seek(TgaHeader::Size + tga.id_length);
// Get header info.
bool rle = false;
bool pal = false;
bool rgb = false;
bool grey = false;
switch( tga.image_type ) {
case TGA_TYPE_RLE_INDEXED:
rle = true;
// no break is intended!
case TGA_TYPE_INDEXED:
if( tga.colormap_type!=1 || tga.colormap_size!=24 || tga.colormap_length>256 ) {
nvDebug( "*** ImageIO::loadTGA: Error, only 24bit paletted images are supported.\n" );
return false;
}
pal = true;
break;
case TGA_TYPE_RLE_RGB:
rle = true;
// no break is intended!
case TGA_TYPE_RGB:
rgb = true;
break;
case TGA_TYPE_RLE_GREY:
rle = true;
// no break is intended!
case TGA_TYPE_GREY:
grey = true;
break;
default:
nvDebug( "*** ImageIO::loadTGA: Error, unsupported image type.\n" );
return false;
}
const uint pixel_size = (tga.pixel_size/8);
nvDebugCheck(pixel_size <= 4);
const uint size = tga.width * tga.height * pixel_size;
// Read palette
uint8 palette[768];
if( pal ) {
nvDebugCheck(tga.colormap_length < 256);
s.serialize(palette, 3 * tga.colormap_length);
}
// Decode image.
uint8 * mem = new uint8[size];
if( rle ) {
// Decompress image in src.
uint8 * dst = mem;
int num = size;
while (num > 0) {
// Get packet header
uint8 c;
s << c;
uint count = (c & 0x7f) + 1;
num -= count * pixel_size;
if (c & 0x80) {
// RLE pixels.
uint8 pixel[4]; // uint8 pixel[pixel_size];
s.serialize( pixel, pixel_size );
do {
memcpy(dst, pixel, pixel_size);
dst += pixel_size;
} while (--count);
}
else {
// Raw pixels.
count *= pixel_size;
//file->Read8(dst, count);
s.serialize(dst, count);
dst += count;
}
}
}
else {
s.serialize(mem, size);
}
// Allocate image.
AutoPtr<Image> img(new Image());
img->allocate(tga.width, tga.height);
int lstep;
Color32 * dst;
if( tga.flags & TGA_ORIGIN_UPPER ) {
lstep = tga.width;
dst = img->pixels();
}
else {
lstep = - tga.width;
dst = img->pixels() + (tga.height-1) * tga.width;
}
// Write image.
uint8 * src = mem;
if( pal ) {
for( int y = 0; y < tga.height; y++ ) {
for( int x = 0; x < tga.width; x++ ) {
uint8 idx = *src++;
dst[x].setBGRA(palette[3*idx+0], palette[3*idx+1], palette[3*idx+2], 0xFF);
}
dst += lstep;
}
}
else if( grey ) {
img->setFormat(Image::Format_ARGB);
for( int y = 0; y < tga.height; y++ ) {
for( int x = 0; x < tga.width; x++ ) {
dst[x].setBGRA(*src, *src, *src, *src);
src++;
}
dst += lstep;
}
}
else {
if( tga.pixel_size == 16 ) {
for( int y = 0; y < tga.height; y++ ) {
for( int x = 0; x < tga.width; x++ ) {
Color555 c = *reinterpret_cast<Color555 *>(src);
uint8 b = (c.b << 3) | (c.b >> 2);
uint8 g = (c.g << 3) | (c.g >> 2);
uint8 r = (c.r << 3) | (c.r >> 2);
dst[x].setBGRA(b, g, r, 0xFF);
src += 2;
}
dst += lstep;
}
}
else if( tga.pixel_size == 24 ) {
for( int y = 0; y < tga.height; y++ ) {
for( int x = 0; x < tga.width; x++ ) {
dst[x].setBGRA(src[0], src[1], src[2], 0xFF);
src += 3;
}
dst += lstep;
}
}
else if( tga.pixel_size == 32 ) {
img->setFormat(Image::Format_ARGB);
for( int y = 0; y < tga.height; y++ ) {
for( int x = 0; x < tga.width; x++ ) {
dst[x].setBGRA(src[0], src[1], src[2], src[3]);
src += 4;
}
dst += lstep;
}
}
}
// free uncompressed data.
delete [] mem;
return img.release();
}
/// Save TGA image.
bool nv::ImageIO::saveTGA(Stream & s, const Image * img)
{
nvCheck(!s.isError());
nvCheck(img != NULL);
nvCheck(img->pixels() != NULL);
TgaFile tga;
tga.head.id_length = 0;
tga.head.colormap_type = 0;
tga.head.image_type = TGA_TYPE_RGB;
tga.head.colormap_index = 0;
tga.head.colormap_length = 0;
tga.head.colormap_size = 0;
tga.head.x_origin = 0;
tga.head.y_origin = 0;
tga.head.width = img->width();
tga.head.height = img->height();
if(img->format() == Image::Format_ARGB) {
tga.head.pixel_size = 32;
tga.head.flags = TGA_ORIGIN_UPPER | TGA_HAS_ALPHA;
}
else {
tga.head.pixel_size = 24;
tga.head.flags = TGA_ORIGIN_UPPER;
}
// @@ Serialize directly.
tga.allocate();
const uint n = img->width() * img->height();
if(img->format() == Image::Format_ARGB) {
for(uint i = 0; i < n; i++) {
Color32 color = img->pixel(i);
tga.mem[4 * i + 0] = color.b;
tga.mem[4 * i + 1] = color.g;
tga.mem[4 * i + 2] = color.r;
tga.mem[4 * i + 3] = color.a;
}
}
else {
for(uint i = 0; i < n; i++) {
Color32 color = img->pixel(i);
tga.mem[3 * i + 0] = color.b;
tga.mem[3 * i + 1] = color.g;
tga.mem[3 * i + 2] = color.r;
}
}
s << tga;
tga.free();
return true;
}
/// Load PSD image.
Image * nv::ImageIO::loadPSD(Stream & s)
{
nvCheck(!s.isError());
nvCheck(s.isLoading());
s.setByteOrder(Stream::BigEndian);
PsdHeader header;
s << header;
if (!header.isValid())
{
printf("invalid header!\n");
return NULL;
}
if (!header.isSupported())
{
printf("unsupported file!\n");
return NULL;
}
int tmp;
// Skip mode data.
s << tmp;
s.seek(s.tell() + tmp);
// Skip image resources.
s << tmp;
s.seek(s.tell() + tmp);
// Skip the reserved data.
s << tmp;
s.seek(s.tell() + tmp);
// Find out if the data is compressed.
// Known values:
// 0: no compression
// 1: RLE compressed
uint16 compression;
s << compression;
if (compression > 1) {
// Unknown compression type.
return NULL;
}
uint channel_num = header.channel_count;
AutoPtr<Image> img(new Image());
img->allocate(header.width, header.height);
if (channel_num < 4)
{
// Clear the image.
img->fill(Color32(0, 0, 0, 0xFF));
}
else
{
// Enable alpha.
img->setFormat(Image::Format_ARGB);
// Ignore remaining channels.
channel_num = 4;
}
const uint pixel_count = header.height * header.width;
static const uint components[4] = {2, 1, 0, 3};
if (compression)
{
s.seek(s.tell() + header.height * header.channel_count * sizeof(uint16));
// Read RLE data.
for (uint channel = 0; channel < channel_num; channel++)
{
uint8 * ptr = (uint8 *)img->pixels() + components[channel];
uint count = 0;
while( count < pixel_count )
{
if (s.isAtEnd()) return NULL;
uint8 c;
s << c;
uint len = c;
if (len < 128)
{
// Copy next len+1 bytes literally.
len++;
count += len;
if (count > pixel_count) return NULL;
while (len != 0)
{
s << *ptr;
ptr += 4;
len--;
}
}
else if (len > 128)
{
// Next -len+1 bytes in the dest are replicated from next source byte.
// (Interpret len as a negative 8-bit int.)
len ^= 0xFF;
len += 2;
count += len;
if (s.isAtEnd() || count > pixel_count) return NULL;
uint8 val;
s << val;
while( len != 0 ) {
*ptr = val;
ptr += 4;
len--;
}
}
else if( len == 128 ) {
// No-op.
}
}
}
}
else
{
// We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
// where each channel consists of an 8-bit value for each pixel in the image.
// Read the data by channel.
for (uint channel = 0; channel < channel_num; channel++)
{
uint8 * ptr = (uint8 *)img->pixels() + components[channel];
// Read the data.
uint count = pixel_count;
while (count != 0)
{
s << *ptr;
ptr += 4;
count--;
}
}
}
return img.release();
}
#if defined(HAVE_PNG)
static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
nvDebugCheck(png_ptr != NULL);
Stream * s = (Stream *)png_ptr->io_ptr;
s->serialize(data, (int)length);
if (s->isError()) {
png_error(png_ptr, "Read Error");
}
}
Image * nv::ImageIO::loadPNG(Stream & s)
{
nvCheck(!s.isError());
// Set up a read buffer and check the library version
png_structp png_ptr;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
// nvDebug( "*** LoadPNG: Error allocating read buffer in file '%s'.\n", name );
return false;
}
// Allocate/initialize a memory block for the image information
png_infop info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
// nvDebug( "*** LoadPNG: Error allocating image information for '%s'.\n", name );
return false;
}
// Set up the error handling
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
// nvDebug( "*** LoadPNG: Error reading png file '%s'.\n", name );
return false;
}
// Set up the I/O functions.
png_set_read_fn(png_ptr, (void*)&s, user_read_data);
// Retrieve the image header information
png_uint_32 width, height;
int bit_depth, color_type, interlace_type;
png_read_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8) {
// Convert indexed images to RGB.
png_set_expand(png_ptr);
}
else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
// Convert grayscale to RGB.
png_set_expand(png_ptr);
}
else if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
// Expand images with transparency to full alpha channels
// so the data will be available as RGBA quartets.
png_set_expand(png_ptr);
}
else if (bit_depth < 8) {
// If we have < 8 scale it up to 8.
//png_set_expand(png_ptr);
png_set_packing(png_ptr);
}
// Reduce bit depth.
if (bit_depth == 16) {
png_set_strip_16(png_ptr);
}
// Represent gray as RGB
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
png_set_gray_to_rgb(png_ptr);
}
// Convert to RGBA filling alpha with 0xFF.
if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
png_set_filler(png_ptr, 0xFF, PNG_FILLER_AFTER);
}
// @todo Choose gamma according to the platform?
double screen_gamma = 2.2;
int intent;
if (png_get_sRGB(png_ptr, info_ptr, &intent)) {
png_set_gamma(png_ptr, screen_gamma, 0.45455);
}
else {
double image_gamma;
if (png_get_gAMA(png_ptr, info_ptr, &image_gamma)) {
png_set_gamma(png_ptr, screen_gamma, image_gamma);
}
else {
png_set_gamma(png_ptr, screen_gamma, 0.45455);
}
}
// Perform the selected transforms.
png_read_update_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
AutoPtr<Image> img(new Image());
img->allocate(width, height);
// Set internal format flags.
if(color_type & PNG_COLOR_MASK_COLOR) {
//img->flags |= PI_IF_HAS_COLOR;
}
if(color_type & PNG_COLOR_MASK_ALPHA) {
//img->flags |= PI_IF_HAS_ALPHA;
img->setFormat(Image::Format_ARGB);
}
// Read the image
uint8 * pixels = (uint8 *)img->pixels();
png_bytep * row_data = new png_bytep[sizeof(png_byte) * height];
for (uint i = 0; i < height; i++) {
row_data[i] = &(pixels[width * 4 * i]);
}
png_read_image(png_ptr, row_data);
delete [] row_data;
// Finish things up
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
// RGBA to BGRA.
uint num = width * height;
for(uint i = 0; i < num; i++)
{
Color32 c = img->pixel(i);
img->pixel(i) = Color32(c.b, c.g, c.r, c.a);
}
// Compute alpha channel if needed.
/*if( img->flags & PI_IU_BUMPMAP || img->flags & PI_IU_ALPHAMAP ) {
if( img->flags & PI_IF_HAS_COLOR && !(img->flags & PI_IF_HAS_ALPHA)) {
img->ComputeAlphaFromColor();
}
}*/
return img.release();
}
#endif // defined(HAVE_PNG)
#if defined(HAVE_JPEG)
static void init_source (j_decompress_ptr /*cinfo*/){
}
static boolean fill_input_buffer (j_decompress_ptr cinfo){
struct jpeg_source_mgr * src = cinfo->src;
static JOCTET FakeEOI[] = { 0xFF, JPEG_EOI };
// Generate warning
nvDebug("jpeglib: Premature end of file\n");
// Insert a fake EOI marker
src->next_input_byte = FakeEOI;
src->bytes_in_buffer = 2;
return TRUE;
}
static void skip_input_data (j_decompress_ptr cinfo, long num_bytes) {
struct jpeg_source_mgr * src = cinfo->src;
if(num_bytes >= (long)src->bytes_in_buffer) {
fill_input_buffer(cinfo);
return;
}
src->bytes_in_buffer -= num_bytes;
src->next_input_byte += num_bytes;
}
static void term_source (j_decompress_ptr /*cinfo*/){
// no work necessary here
}
Image * nv::ImageIO::loadJPG(Stream & s)
{
nvCheck(!s.isError());
// Read the entire file.
Array<uint8> byte_array;
byte_array.resize(s.size());
s.serialize(byte_array.unsecureBuffer(), s.size());
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
cinfo.src = (struct jpeg_source_mgr *) (*cinfo.mem->alloc_small)
((j_common_ptr) &cinfo, JPOOL_PERMANENT, sizeof(struct jpeg_source_mgr));
cinfo.src->init_source = init_source;
cinfo.src->fill_input_buffer = fill_input_buffer;
cinfo.src->skip_input_data = skip_input_data;
cinfo.src->resync_to_restart = jpeg_resync_to_restart; // use default method
cinfo.src->term_source = term_source;
cinfo.src->bytes_in_buffer = byte_array.size();
cinfo.src->next_input_byte = byte_array.buffer();
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
/*
cinfo.do_fancy_upsampling = FALSE; // fast decompression
cinfo.dct_method = JDCT_FLOAT; // Choose floating point DCT method.
*/
uint8 * tmp_buffer = new uint8 [cinfo.output_width * cinfo.output_height * cinfo.num_components];
uint8 * scanline = tmp_buffer;
while( cinfo.output_scanline < cinfo.output_height ){
int num_scanlines = jpeg_read_scanlines (&cinfo, &scanline, 1);
scanline += num_scanlines * cinfo.output_width * cinfo.num_components;
}
jpeg_finish_decompress(&cinfo);
AutoPtr<Image> img(new Image());
img->allocate(cinfo.output_width, cinfo.output_height);
Color32 * dst = img->pixels();
const int size = img->height() * img->width();
const uint8 * src = tmp_buffer;
if( cinfo.num_components == 3 ) {
img->setFormat(Image::Format_RGB);
for( int i = 0; i < size; i++ ) {
*dst++ = Color32(src[0], src[1], src[2]);
src += 3;
}
}
else {
img->setFormat(Image::Format_ARGB);
for( int i = 0; i < size; i++ ) {
*dst++ = Color32(*src, *src, *src, *src);
src++;
}
}
delete [] tmp_buffer;
jpeg_destroy_decompress (&cinfo);
return img.release();
}
#endif // defined(HAVE_JPEG)
#if defined(HAVE_TIFF)
/*
static tsize_t tiffReadWriteProc(thandle_t h, tdata_t ptr, tsize_t size)
{
Stream * s = (Stream *)h;
nvDebugCheck(s != NULL);
s->serialize(ptr, size);
return size;
}
static toff_t tiffSeekProc(thandle_t h, toff_t offset, int whence)
{
Stream * s = (Stream *)h;
nvDebugCheck(s != NULL);
if (!s->isSeekable())
{
return (toff_t)-1;
}
if (whence == SEEK_SET)
{
s->seek(offset);
}
else if (whence == SEEK_CUR)
{
s->seek(s->tell() + offset);
}
else if (whence == SEEK_END)
{
s->seek(s->size() + offset);
}
return s->tell();
}
static int tiffCloseProc(thandle_t)
{
return 0;
}
static toff_t tiffSizeProc(thandle_t h)
{
Stream * s = (Stream *)h;
nvDebugCheck(s != NULL);
return s->size();
}
static int tiffMapFileProc(thandle_t, tdata_t*, toff_t*)
{
// @@ TODO, Implement these functions.
return -1;
}
static void tiffUnmapFileProc(thandle_t, tdata_t, toff_t)
{
// @@ TODO, Implement these functions.
}
*/
FloatImage * nv::ImageIO::loadFloatTIFF(const char * fileName, Stream & s)
{
nvCheck(!s.isError());
TIFF * tif = TIFFOpen(fileName, "r");
//TIFF * tif = TIFFClientOpen(fileName, "r", &s, tiffReadWriteProc, tiffReadWriteProc, tiffSeekProc, tiffCloseProc, tiffSizeProc, tiffMapFileProc, tiffUnmapFileProc);
if (!tif)
{
nvDebug("Can't open '%s' for reading\n", fileName);
return NULL;
}
::uint16 spp, bpp, format;
::uint32 width, height;
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bpp);
TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &format);
if (bpp != 8 && bpp != 16 && bpp != 32) {
nvDebug("Can't load '%s', only 1 sample per pixel supported\n", fileName);
TIFFClose(tif);
return NULL;
}
AutoPtr<FloatImage> fimage(new FloatImage());
fimage->allocate(spp, width, height);
int linesize = TIFFScanlineSize(tif);
tdata_t buf = (::uint8 *)nv::mem::malloc(linesize);
for (uint y = 0; y < height; y++)
{
TIFFReadScanline(tif, buf, y, 0);
for (uint c=0; c<spp; c++ )
{
float * dst = fimage->scanline(y, c);
for(uint x = 0; x < width; x++)
{
if (bpp == 8)
{
dst[x] = float(((::uint8 *)buf)[x*spp+c]) / float(0xFF);
}
else if (bpp == 16)
{
dst[x] = float(((::uint16 *)buf)[x*spp+c]) / float(0xFFFF);
}
else if (bpp == 32)
{
if (format==SAMPLEFORMAT_IEEEFP)
{
dst[x] = float(((float *)buf)[x*spp+c]);
}
else
{
dst[x] = float(((::uint32 *)buf)[x*spp+c] >> 8) / float(0xFFFFFF);
}
}
}
}
}
nv::mem::free(buf);
TIFFClose(tif);
return fimage.release();
}