-
Notifications
You must be signed in to change notification settings - Fork 0
/
imageio.c
2185 lines (1880 loc) · 69.1 KB
/
imageio.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
/**
* @file imageio.c
* @brief Implements ReadImage and WriteImage functions
* @author Pascal Getreuer <[email protected]>
*
* Two high-level functions are provided, \c ReadImage and \c WriteImage, for
* reading and writing image BMP, JPEG, PNG, and TIFF files. The desired
* format of the image data can be specified to \c ReadImage for how to return
* the data (and similarly to \c WriteImage for how it should interpret the
* data). Formatting options allow specifying the datatype of the components,
* conversion to grayscale, channel ordering, interleaved vs. planar, and
* row-major vs. column-major.
*
* \c ReadImage automatically detects the format of the image being read so
* that the format does not need to be supplied explicitly. \c WriteImage
* infers the file format from the file extension.
*
* Also included is a function \c IdentifyImageType to guess the file type (BMP,
* JPEG, PNG, TIFF, and a few other formats) from the file header's magic
* numbers without reading the image.
*
* Support for BMP reading and writing is native: BMP reading supports 1-, 2-,
* 4-, 8-, 16-, 32-bit uncompressed, RLE, and bitfield images; BMP writing is
* limited to 24-bit uncompressed. The implementation calls libjpeg, libpng,
* and libtiff to handle JPEG, PNG, and TIFF images.
*
*
* Copyright (c) 2010-2011, Pascal Getreuer
* All rights reserved.
*
* This program is free software: you can use, modify and/or
* redistribute it under the terms of the simplified BSD License. You
* should have received a copy of this license along this program. If
* not, see <http://www.opensource.org/licenses/bsd-license.html>.
*/
#include <string.h>
#include <ctype.h>
#include "imageio.h"
#ifdef LIBPNG_SUPPORT
#include <png.h>
#include <zlib.h>
#if PNG_LIBPNG_VER < 10400
/* For compatibility with older libpng */
#define png_set_expand_gray_1_2_4_to_8 png_set_gray_1_2_4_to_8
#endif
#endif
#ifdef LIBTIFF_SUPPORT
#include <tiffio.h>
#endif
#ifdef LIBJPEG_SUPPORT
#include <jpeglib.h>
#include <setjmp.h>
#endif
/** @brief Buffer size to use for BMP file I/O */
#define FILE_BUFFER_CAPACITY (1024*4)
#define ROUNDCLAMPF(x) ((x < 0.0f) ? 0 : \
((x > 1.0f) ? 255 : (uint8_t)(255.0f*(x) + 0.5f)))
#define ROUNDCLAMP(x) ((x < 0.0) ? 0 : \
((x > 1.0) ? 255 : (uint8_t)(255.0*(x) + 0.5)))
/** @brief Case-insensitive test to see if String ends with Suffix */
static int StringEndsWith(const char *String, const char *Suffix)
{
unsigned i, StringLength = strlen(String), SuffixLength = strlen(Suffix);
if(StringLength < SuffixLength)
return 0;
String += StringLength - SuffixLength;
for(i = 0; i < SuffixLength; i++)
if(tolower(String[i]) != tolower(Suffix[i]))
return 0;
return 1;
}
/** @brief Fill an image with a color */
static void FillImage(uint32_t *Image, int Width, int Height, uint32_t Color)
{
int x, y;
if(Image)
for(y = 0; y < Height; y++, Image += Width)
for(x = 0; x < Width; x++)
Image[x] = Color;
}
/**
* @brief Check use of color and alpha, and count number of distinct colors
* @param NumColors set by the routine to the number of unique colors
* @param UseColor set to 1 if the image is not grayscale
* @param UseAlpha set to 1 if the image alpha is not constant 255
* @param Image pointer to U8 RGBA interleaved image data
* @param Width, Height dimensions of the image
* @return pointer to a color palette with NumColors entries or NULL if the
* number of distinct colors exceeds 256.
*
* This routine checks whether an RGBA image makes use of color and alpha, and
* constructs a palette if the number of distinct colors is 256 or fewer. This
* information is useful for writing image files with smaller file size.
*/
static uint32_t *GetImagePalette(int *NumColors, int *UseColor, int *UseAlpha,
const uint32_t *Image, int Width, int Height)
{
const int MaxColors = 256;
uint32_t *Palette = NULL;
uint32_t Pixel;
int x, y, i, Red, Green, Blue, Alpha;
if(!UseColor || !NumColors || !UseAlpha)
return NULL;
else if(!Image
|| !(Palette = (uint32_t *)Malloc(sizeof(uint32_t)*MaxColors)))
{
*NumColors = -1;
*UseColor = *UseAlpha = 1;
return NULL;
}
*NumColors = *UseColor = *UseAlpha = 0;
for(y = 0; y < Height; y++)
{
for(x = 0; x < Width; x++)
{
Pixel = *(Image++);
Red = ((uint8_t *)&Pixel)[0];
Green = ((uint8_t *)&Pixel)[1];
Blue = ((uint8_t *)&Pixel)[2];
Alpha = ((uint8_t *)&Pixel)[3];
if(Red != Green || Red != Blue) /* Check color */
*UseColor = 1;
if(Alpha != 255) /* Check alpha */
*UseAlpha = 1;
/* Check Palette colors (if *NumColors != -1) */
for(i = 0; i < *NumColors; i++)
if(Pixel == Palette[i])
break;
if(i == *NumColors)
{
if(i < MaxColors)
{ /* Add new color to Palette */
Palette[i] = Pixel;
(*NumColors)++;
}
else
{ /* Maximum size for Palette exceeded */
Free(Palette);
Palette = NULL;
*NumColors = -1; /* Don't check Palette colors */
}
}
}
}
return Palette;
}
/** @brief Read a 16-bit little Endian word from File */
static uint16_t ReadWordLE(FILE *File)
{
uint16_t w;
w = (uint16_t) getc(File);
w |= ((uint16_t) getc(File) << 8);
return w;
}
/** @brief Read a 32-bit little Endian double word from File */
static uint32_t ReadDWordLE(FILE *File)
{
uint32_t dw;
dw = (uint32_t) getc(File);
dw |= ((uint32_t) getc(File) << 8);
dw |= ((uint32_t) getc(File) << 16);
dw |= ((uint32_t) getc(File) << 24);
return dw;
}
/** @brief Write a 16-bit word in little Endian format */
static void WriteWordLE(uint16_t w, FILE *File)
{
putc(w & 0xFF, File);
putc((w & 0xFF00) >> 8, File);
}
/** @brief Write a 32-bit double word in little Endian format */
static void WriteDWordLE(uint32_t dw, FILE *File)
{
putc(dw & 0xFF, File);
putc((dw & 0xFF00) >> 8, File);
putc((dw & 0xFF0000) >> 16, File);
putc((dw & 0xFF000000) >> 24, File);
}
/** @brief Internal function for reading 1-bit BMP */
static int ReadBmp1Bit(uint32_t *Image, int Width, int Height, FILE *File, const uint32_t *Palette)
{
int RowPadding = (-(Width+7)/8)&3;
int x, y, Bit;
unsigned Code;
Image += ((long int)Width)*((long int)Height - 1);
for(y = Height; y; y--, Image -= Width)
{
if(feof(File))
return 0;
for(x = 0; x < Width;)
{
Code = getc(File);
for(Bit = 7; Bit >= 0 && x < Width; Bit--, Code <<= 1)
Image[x++] = Palette[(Code & 0x80) ? 1:0];
}
for(x = RowPadding; x; x--)
getc(File); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** @brief Internal function for reading 4-bit BMP */
static int ReadBmp4Bit(uint32_t *Image, int Width, int Height, FILE *File, const uint32_t *Palette)
{
int RowPadding = (-(Width+1)/2)&3;
int x, y;
unsigned Code;
Image += ((long int)Width)*((long int)Height - 1);
for(y = Height; y; y--, Image -= Width)
{
if(feof(File))
return 0;
for(x = 0; x < Width;)
{
Code = getc(File);
Image[x++] = Palette[(Code & 0xF0) >> 4];
if(x < Width)
Image[x++] = Palette[Code & 0x0F];
}
for(x = RowPadding; x; x--)
getc(File); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** @brief Internal function for reading 4-bit RLE-compressed BMP */
static int ReadBmp4BitRle(uint32_t *Image, int Width, int Height, FILE *File, const uint32_t *Palette)
{
int x, y, dy, k;
unsigned Count, Value;
uint32_t ColorH, ColorL;
FillImage(Image, Width, Height, Palette[0]);
Image += ((long int)Width)*((long int)Height - 1);
for(x = 0, y = Height; y;)
{
if(feof(File))
return 0;
Count = getc(File);
Value = getc(File);
if(!Count)
{ /* Count = 0 is the escape code */
switch(Value)
{
case 0: /* End of line */
Image -= Width;
x = 0;
y--;
break;
case 1: /* End of bitmap */
return 1;
case 2: /* Delta */
x += getc(File);
dy = getc(File);
y -= dy;
Image -= dy*Width;
if(x >= Width || y < 0)
return 0;
break;
default: /* Read a run of uncompressed data (Value = length of run) */
Count = k = Value;
if(x >= Width)
return 0;
do
{
Value = getc(File);
Image[x++] = Palette[(Value & 0xF0) >> 4];
if(x >= Width)
break;
if(--k)
{
Image[x++] = Palette[Value & 0x0F];
k--;
if(x >= Width)
break;
}
}while(k);
if(((Count + 1)/2) & 1)
getc(File); /* Padding for word align */
}
}
else
{ /* Run of pixels (Count = length of run) */
ColorH = Palette[(Value & 0xF0) >> 4];
ColorL = Palette[Value & 0xF];
if(x >= Width)
return 0;
do
{
Image[x++] = ColorH;
Count--;
if(x >= Width)
break;
if(Count)
{
Image[x++] = ColorL;
Count--;
if(x >= Width)
break;
}
}while(Count);
}
}
return 1;
}
/** @brief Internal function for reading 8-bit BMP */
static int ReadBmp8Bit(uint32_t *Image, int Width, int Height, FILE *File, const uint32_t *Palette)
{
int RowPadding = (-Width)&3;
int x, y;
Image += ((long int)Width)*((long int)Height - 1);
for(y = Height; y; y--, Image -= Width)
{
if(feof(File))
return 0;
for(x = 0; x < Width; x++)
Image[x] = Palette[getc(File) & 0xFF];
for(x = RowPadding; x; x--)
getc(File); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** @brief Internal function for reading 8-bit RLE-compressed BMP */
static int ReadBmp8BitRle(uint32_t *Image, int Width, int Height, FILE *File, const uint32_t *Palette)
{
int x, y, dy, k;
unsigned Count, Value;
uint32_t Color;
FillImage(Image, Width, Height, Palette[0]);
Image += ((long int)Width)*((long int)Height - 1);
for(x = 0, y = Height; y;)
{
if(feof(File))
return 0;
Count = getc(File);
Value = getc(File);
if(!Count)
{ /* Count = 0 is the escape code */
switch(Value)
{
case 0: /* End of line */
Image -= Width;
x = 0;
y--;
break;
case 1: /* End of bitmap */
return 1;
case 2: /* Delta */
x += getc(File);
dy = getc(File);
y -= dy;
Image -= dy*Width;
if(x >= Width || y < 0)
return 0;
break;
default: /* Read a run of uncompressed data (Value = length of run) */
Count = k = Value;
do
{
if(x >= Width)
break;
Image[x++] = Palette[getc(File) & 0xFF];
}while(--k);
if(Count&1)
getc(File); /* Padding for word align */
}
}
else
{ /* Run of pixels equal to Value (Count = length of run) */
Color = Palette[Value & 0xFF];
do
{
if(x >= Width)
break;
Image[x++] = Color;
}while(--Count);
}
}
return 1;
}
/** @brief Internal function for reading 24-bit BMP */
static int ReadBmp24Bit(uint32_t *Image, int Width, int Height, FILE *File)
{
uint8_t *ImagePtr = (uint8_t *)Image;
int RowPadding = (-3*Width)&3;
int x, y;
Width <<= 2;
ImagePtr += ((long int)Width)*((long int)Height - 1);
for(y = Height; y; y--, ImagePtr -= Width)
{
if(feof(File))
return 0;
for(x = 0; x < Width; x += 4)
{
ImagePtr[x+3] = 255; /* Set alpha */
ImagePtr[x+2] = getc(File); /* Read blue component */
ImagePtr[x+1] = getc(File); /* Read green component */
ImagePtr[x+0] = getc(File); /* Read red component */
}
for(x = RowPadding; x; x--)
getc(File); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** @brief Internal function for determining bit shifts in bitfield BMP */
static void GetMaskShifts(uint32_t Mask, int *LeftShift, int *RightShift)
{
int Shift = 0, BitCount = 0;
if(!Mask)
{
*LeftShift = 0;
*RightShift = 0;
return;
}
while(!(Mask & 1)) /* Find the first true bit */
{
Mask >>= 1;
++Shift;
}
/* Adjust the result for scaling to 8-bit quantities */
while(Mask & 1) /* Count the number of true bits */
{
Mask >>= 1;
++BitCount;
}
/* Compute a signed shift (right is positive) */
Shift += BitCount - 8;
if(Shift >= 0)
{
*LeftShift = 0;
*RightShift = Shift;
}
else
{
*LeftShift = -Shift;
*RightShift = 0;
}
}
/** @brief Internal function for reading 16-bit BMP */
static int ReadBmp16Bit(uint32_t *Image, int Width, int Height, FILE *File,
uint32_t RedMask, uint32_t GreenMask, uint32_t BlueMask, uint32_t AlphaMask)
{
uint8_t *ImagePtr = (uint8_t *)Image;
uint32_t Code;
int RowPadding = (-2*Width)&3;
int RedLeftShift, GreenLeftShift, BlueLeftShift, AlphaLeftShift;
int RedRightShift, GreenRightShift, BlueRightShift, AlphaRightShift;
int x, y;
GetMaskShifts(RedMask, &RedLeftShift, &RedRightShift);
GetMaskShifts(GreenMask, &GreenLeftShift, &GreenRightShift);
GetMaskShifts(BlueMask, &BlueLeftShift, &BlueRightShift);
GetMaskShifts(AlphaMask, &AlphaLeftShift, &AlphaRightShift);
Width <<= 2;
ImagePtr += ((long int)Width)*((long int)Height - 1);
for(y = Height; y; y--, ImagePtr -= Width)
{
if(feof(File))
return 0;
for(x = 0; x < Width; x += 4)
{
Code = ReadWordLE(File);
/* By the Windows 4.x BMP specification, color component masks must be contiguous
[http://www.fileformat.info/format/bmp/egff.htm]. So we can decode the bitfields
by bitwise AND with the mask and applying a bitshift.*/
ImagePtr[x+3] = ((Code & AlphaMask) >> AlphaRightShift) << AlphaLeftShift;
ImagePtr[x+2] = ((Code & BlueMask ) >> BlueRightShift ) << BlueLeftShift;
ImagePtr[x+1] = ((Code & GreenMask) >> GreenRightShift) << GreenLeftShift;
ImagePtr[x+0] = ((Code & RedMask ) >> RedRightShift ) << RedLeftShift;
}
for(x = RowPadding; x; x--)
getc(File); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** @brief Internal function for reading 32-bit BMP */
static int ReadBmp32Bit(uint32_t *Image, int Width, int Height, FILE *File,
uint32_t RedMask, uint32_t GreenMask, uint32_t BlueMask, uint32_t AlphaMask)
{
uint8_t *ImagePtr;
uint32_t Code;
int RedLeftShift, GreenLeftShift, BlueLeftShift, AlphaLeftShift;
int RedRightShift, GreenRightShift, BlueRightShift, AlphaRightShift;
int x, y;
GetMaskShifts(RedMask, &RedLeftShift, &RedRightShift);
GetMaskShifts(GreenMask, &GreenLeftShift, &GreenRightShift);
GetMaskShifts(BlueMask, &BlueLeftShift, &BlueRightShift);
GetMaskShifts(AlphaMask, &AlphaLeftShift, &AlphaRightShift);
Width <<= 2;
ImagePtr = (uint8_t *)Image + ((long int)Width)*((long int)Height - 1);
for(y = Height; y; y--, ImagePtr -= Width)
{
if(feof(File))
return 0;
for(x = 0; x < Width; x += 4)
{
Code = ReadDWordLE(File);
/* By the Windows 4.x BMP specification, color component masks must be contiguous
[http://www.fileformat.info/format/bmp/egff.htm]. So we can decode the bitfields
by bitwise AND with the mask and applying a bitshift.*/
ImagePtr[x+3] = ((Code & AlphaMask) >> AlphaRightShift) << AlphaLeftShift;
ImagePtr[x+2] = ((Code & BlueMask ) >> BlueRightShift ) << BlueLeftShift;
ImagePtr[x+1] = ((Code & GreenMask) >> GreenRightShift) << GreenLeftShift;
ImagePtr[x+0] = ((Code & RedMask ) >> RedRightShift ) << RedLeftShift;
}
}
return 1;
}
/**
* @brief Read a BMP (Windows Bitmap) image file as RGBA data
*
* @param Image, Width, Height pointers to be filled with the pointer
* to the image data and the image dimensions.
* @param File stdio FILE pointer pointing to the beginning of the BMP file
*
* @return 1 on success, 0 on failure
*
* This function is called by \c ReadImage to read BMP images. Before calling
* \c ReadBmp, the caller should open \c File as a FILE pointer in binary read
* mode. When \c ReadBmp is complete, the caller should close \c File.
*/
static int ReadBmp(uint32_t **Image, int *Width, int *Height, FILE *File)
{
uint32_t *Palette = NULL;
uint8_t *PalettePtr;
long int ImageDataOffset, InfoSize;
unsigned i, NumPlanes, BitsPerPixel, Compression, NumColors;
uint32_t RedMask, GreenMask, BlueMask, AlphaMask;
int Success = 0, Os2Bmp;
uint8_t Magic[2];
*Image = NULL;
*Width = *Height = 0;
fseek(File, 0, SEEK_SET);
Magic[0] = getc(File);
Magic[1] = getc(File);
if(!(Magic[0] == 0x42 && Magic[1] == 0x4D) /* Verify the magic numbers */
|| fseek(File, 8, SEEK_CUR)) /* Skip the reserved fields */
{
ErrorMessage("Invalid BMP header.\n");
goto Catch;
}
ImageDataOffset = ReadDWordLE(File);
InfoSize = ReadDWordLE(File);
/* Read the info header */
if(InfoSize < 12)
{
ErrorMessage("Invalid BMP info header.\n");
goto Catch;
}
if((Os2Bmp = (InfoSize == 12))) /* This is an OS/2 V1 infoheader */
{
*Width = (int)ReadWordLE(File);
*Height = (int)ReadWordLE(File);
NumPlanes = (unsigned)ReadWordLE(File);
BitsPerPixel = (unsigned)ReadWordLE(File);
Compression = 0;
NumColors = 0;
RedMask = 0x00FF0000;
GreenMask = 0x0000FF00;
BlueMask = 0x000000FF;
AlphaMask = 0xFF000000;
}
else
{
*Width = abs((int)ReadDWordLE(File));
*Height = abs((int)ReadDWordLE(File));
NumPlanes = (unsigned)ReadWordLE(File);
BitsPerPixel = (unsigned)ReadWordLE(File);
Compression = (unsigned)ReadDWordLE(File);
fseek(File, 12, SEEK_CUR);
NumColors = (unsigned)ReadDWordLE(File);
fseek(File, 4, SEEK_CUR);
RedMask = ReadDWordLE(File);
GreenMask = ReadDWordLE(File);
BlueMask = ReadDWordLE(File);
AlphaMask = ReadDWordLE(File);
}
/* Check for problems or unsupported compression modes */
if(*Width > MAX_IMAGE_SIZE || *Height > MAX_IMAGE_SIZE)
{
ErrorMessage("Image dimensions exceed MAX_IMAGE_SIZE.\n");
goto Catch;
}
if(feof(File) || NumPlanes != 1 || Compression > 3)
goto Catch;
/* Allocate the image data */
if(!(*Image = (uint32_t *)Malloc(sizeof(uint32_t)*((long int)*Width)*((long int)*Height))))
goto Catch;
/* Read palette */
if(BitsPerPixel <= 8)
{
fseek(File, 14 + InfoSize, SEEK_SET);
if(!NumColors)
NumColors = 1 << BitsPerPixel;
if(!(Palette = (uint32_t *)Malloc(sizeof(uint32_t)*256)))
goto Catch;
for(i = 0, PalettePtr = (uint8_t *)Palette; i < NumColors; i++)
{
PalettePtr[3] = 255; /* Set alpha */
PalettePtr[2] = getc(File); /* Read blue component */
PalettePtr[1] = getc(File); /* Read green component */
PalettePtr[0] = getc(File); /* Read red component */
PalettePtr += 4;
if(!Os2Bmp)
getc(File); /* Skip extra byte (for non-OS/2 bitmaps) */
}
for(; i < 256; i++) /* Fill the rest of the palette with the first color */
Palette[i] = Palette[0];
}
if(fseek(File, ImageDataOffset, SEEK_SET) || feof(File))
{
ErrorMessage("File error.\n");
goto Catch;
}
/*** Read the bitmap image data ***/
switch(Compression)
{
case 0: /* Uncompressed data */
switch(BitsPerPixel)
{
case 1: /* Read 1-bit uncompressed indexed data */
Success = ReadBmp1Bit(*Image, *Width, *Height, File, Palette);
break;
case 4: /* Read 4-bit uncompressed indexed data */
Success = ReadBmp4Bit(*Image, *Width, *Height, File, Palette);
break;
case 8: /* Read 8-bit uncompressed indexed data */
Success = ReadBmp8Bit(*Image, *Width, *Height, File, Palette);
break;
case 24: /* Read 24-bit BGR image data */
Success = ReadBmp24Bit(*Image, *Width, *Height, File);
break;
case 16: /* Read 16-bit data */
Success = ReadBmp16Bit(*Image, *Width, *Height, File,
0x001F << 10, 0x001F << 5, 0x0001F, 0);
break;
case 32: /* Read 32-bit BGRA image data */
Success = ReadBmp32Bit(*Image, *Width, *Height, File,
0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
break;
}
break;
case 1: /* 8-bit RLE */
if(BitsPerPixel == 8)
Success = ReadBmp8BitRle(*Image, *Width, *Height, File, Palette);
break;
case 2: /* 4-bit RLE */
if(BitsPerPixel == 4)
Success = ReadBmp4BitRle(*Image, *Width, *Height, File, Palette);
break;
case 3: /* Bitfields data */
switch(BitsPerPixel)
{
case 16: /* Read 16-bit bitfields data */
Success = ReadBmp16Bit(*Image, *Width, *Height, File,
RedMask, GreenMask, BlueMask, AlphaMask);
break;
case 32: /* Read 32-bit bitfields data */
Success = ReadBmp32Bit(*Image, *Width, *Height, File,
RedMask, GreenMask, BlueMask, AlphaMask);
break;
}
break;
}
if(!Success)
ErrorMessage("Error reading BMP data.\n");
Catch: /* There was a problem, clean up and exit */
if(Palette)
Free(Palette);
if(!Success && *Image)
Free(*Image);
return Success;
}
/**
* @brief Write a BMP image
*
* @param Image pointer to RGBA image data
* @param Width, Height the image dimensions
* @param File stdio FILE pointer
*
* @return 1 on success, 0 on failure
*
* This function is called by \c WriteImage to write BMP images. The caller
* should open \c File in binary write mode. When \c WriteBmp is complete,
* the caller should close \c File.
*
* The image is generally saved in uncompressed 24-bit RGB format. But where
* possible, the image is saved using an 8-bit palette for a substantial
* decrease in file size. The image data is always saved losslessly.
*
* @note The alpha channel is lost when saving to BMP. It is possible to write
* the alpha channel in a 32-bit BMP image, however, such images are not
* widely supported. RGB 24-bit BMP on the other hand is well supported.
*/
static int WriteBmp(const uint32_t *Image, int Width, int Height, FILE *File)
{
const uint8_t *ImagePtr = (uint8_t *)Image;
uint32_t *Palette = NULL;
uint32_t Pixel;
long int ImageSize;
int UsePalette, NumColors, UseColor, UseAlpha;
int x, y, i, RowPadding, Success = 0;
if(!Image)
return 0;
Palette = GetImagePalette(&NumColors, &UseColor, &UseAlpha,
Image, Width, Height);
/* Decide whether to use 8-bit palette or 24-bit RGB format */
if(Palette && 2*NumColors < Width*Height)
UsePalette = 1;
else
UsePalette = NumColors = 0;
/* Tell File to use buffering */
setvbuf(File, 0, _IOFBF, FILE_BUFFER_CAPACITY);
if(UsePalette)
{
RowPadding = (-Width)&3;
ImageSize = (Width + RowPadding)*((long int)Height);
}
else
{
RowPadding = (-3*Width)&3;
ImageSize = (3*Width + RowPadding)*((long int)Height);
}
/*** Write the header ***/
/* Write the BMP header */
putc(0x42, File); /* Magic numbers */
putc(0x4D, File);
/* Filesize */
WriteDWordLE(54 + 4*NumColors + ImageSize, File);
WriteDWordLE(0, File); /* Reserved fields */
WriteDWordLE(54 + 4*NumColors, File); /* Image data offset */
/* Write the infoheader */
WriteDWordLE(40, File); /* Infoheader size */
WriteDWordLE(Width, File); /* Image width */
WriteDWordLE(Height, File); /* Image height */
WriteWordLE(1, File); /* Number of colorplanes */
WriteWordLE((UsePalette) ? 8:24, File); /* Bits per pixel */
WriteDWordLE(0, File); /* Compression method (none) */
WriteDWordLE(ImageSize, File); /* Image size */
WriteDWordLE(2835, File); /* HResolution (2835=72dpi) */
WriteDWordLE(2835, File); /* VResolution */
/* Number of colors */
WriteDWordLE((!UsePalette || NumColors == 256) ? 0:NumColors, File);
WriteDWordLE(0, File); /* Important colors */
if(ferror(File))
{
ErrorMessage("Error during write to file.\n");
goto Catch;
}
if(UsePalette)
{ /* Write the Palette */
for(i = 0; i < NumColors; i++)
{
Pixel = Palette[i];
putc(((uint8_t *)&Pixel)[2], File); /* Blue */
putc(((uint8_t *)&Pixel)[1], File); /* Green */
putc(((uint8_t *)&Pixel)[0], File); /* Red */
putc(0, File); /* Unused */
}
}
/* Write the image data */
Width <<= 2;
ImagePtr += ((long int)Width)*((long int)Height - 1);
for(y = Height; y; y--, ImagePtr -= Width)
{
if(UsePalette)
{ /* 8-bit palette image data */
for(x = 0; x < Width; x += 4)
{
Pixel = *((uint32_t *)(ImagePtr + x));
for(i = 0; i < NumColors; i++)
if(Pixel == Palette[i])
break;
putc(i, File);
}
}
else
{ /* 24-bit RGB image data */
for(x = 0; x < Width; x += 4)
{
putc(ImagePtr[x+2], File); /* Write blue component */
putc(ImagePtr[x+1], File); /* Write green component */
putc(ImagePtr[x+0], File); /* Write red component */
}
}
for(x = RowPadding; x; x--) /* Write row padding */
putc(0, File);
}
if(ferror(File))
{
ErrorMessage("Error during write to file.\n");
goto Catch;
}
Success = 1;
Catch:
if(Palette)
Free(Palette);
return Success;
}
#ifdef LIBJPEG_SUPPORT
/**
* @brief Struct that assists in customizing libjpeg error management
*
* This struct is used in combination with JerrExit (static function defined
* here in utiljpeg.c) to have control over how libjpeg errors are displayed.
*/
typedef struct{
struct jpeg_error_mgr pub;
jmp_buf jmpbuf;
} hooked_jerr;
/** @brief Callback for displaying libjpeg errors */
METHODDEF(void) JerrExit(j_common_ptr cinfo)
{
hooked_jerr *Jerr = (hooked_jerr *) cinfo->err;
(*cinfo->err->output_message)(cinfo);
longjmp(Jerr->jmpbuf, 1);
}
/**
* @brief Read a JPEG (Joint Picture Experts Group) image file as RGBA data
*
* @param Image, Width, Height pointers to be filled with the pointer
* to the image data and the image dimensions.
* @param File stdio FILE pointer pointing to the beginning of the BMP file
*
* @return 1 on success, 0 on failure
*
* This function is called by \c ReadImage to read JPEG images. Before calling
* \c ReadJpeg, the caller should open \c File as a FILE pointer in binary read
* mode. When \c ReadJpeg is complete, the caller should close \c File.
*/
static int ReadJpeg(uint32_t **Image, int *Width, int *Height, FILE *File)
{
struct jpeg_decompress_struct cinfo;
hooked_jerr Jerr;
JSAMPARRAY Buffer;
uint8_t *ImagePtr;
unsigned i, RowSize;
*Image = 0;