forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbmpdataset.cpp
1701 lines (1508 loc) · 61.5 KB
/
bmpdataset.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
/******************************************************************************
*
* Project: Microsoft Windows Bitmap
* Purpose: Read/write MS Windows Device Independent Bitmap (DIB) files
* and OS/2 Presentation Manager bitmaps v. 1.x and v. 2.x
* Author: Andrey Kiselev, [email protected]
*
******************************************************************************
* Copyright (c) 2002, Andrey Kiselev <[email protected]>
* Copyright (c) 2007-2010, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_string.h"
#include "gdal_frmts.h"
#include "gdal_pam.h"
#include <limits>
// Enable if you want to see lots of BMP debugging output.
// #define BMP_DEBUG
enum BMPType
{
BMPT_WIN4, // BMP used in Windows 3.0/NT 3.51/95
BMPT_WIN5, // BMP used in Windows NT 4.0/98/Me/2000/XP
BMPT_OS21, // BMP used in OS/2 PM 1.x
BMPT_OS22 // BMP used in OS/2 PM 2.x
};
// Bitmap file consists of a BMPFileHeader structure followed by a
// BMPInfoHeader structure. An array of BMPColorEntry structures (also called
// a colour table) follows the bitmap information header structure. The colour
// table is followed by a second array of indexes into the colour table (the
// actual bitmap data). Data may be compressed, for 4-bpp and 8-bpp used RLE
// compression.
//
// +---------------------+
// | BMPFileHeader |
// +---------------------+
// | BMPInfoHeader |
// +---------------------+
// | BMPColorEntry array |
// +---------------------+
// | Colour-index array |
// +---------------------+
//
// All numbers stored in Intel order with least significant byte first.
enum BMPComprMethod
{
BMPC_RGB = 0L, // Uncompressed
BMPC_RLE8 = 1L, // RLE for 8 bpp images
BMPC_RLE4 = 2L, // RLE for 4 bpp images
BMPC_BITFIELDS = 3L, // Bitmap is not compressed and the colour table
// consists of three DWORD color masks that specify
// the red, green, and blue components of each pixel.
// This is valid when used with 16- and 32-bpp bitmaps.
BMPC_JPEG = 4L, // Indicates that the image is a JPEG image.
BMPC_PNG = 5L // Indicates that the image is a PNG image.
};
enum BMPLCSType // Type of logical color space.
{
BMPLT_CALIBRATED_RGB = 0, // This value indicates that endpoints and gamma
// values are given in the appropriate fields.
BMPLT_DEVICE_RGB = 1,
BMPLT_DEVICE_CMYK = 2
};
typedef struct
{
// cppcheck-suppress unusedStructMember
GInt32 iCIEX;
// cppcheck-suppress unusedStructMember
GInt32 iCIEY;
// cppcheck-suppress unusedStructMember
GInt32 iCIEZ;
} BMPCIEXYZ;
typedef struct // This structure contains the x, y, and z
{ // coordinates of the three colors that correspond
// cppcheck-suppress unusedStructMember
BMPCIEXYZ iCIERed; // to the red, green, and blue endpoints for
// cppcheck-suppress unusedStructMember
BMPCIEXYZ iCIEGreen; // a specified logical color space.
// cppcheck-suppress unusedStructMember
BMPCIEXYZ iCIEBlue;
} BMPCIEXYZTriple;
typedef struct
{
GByte bType[2]; // Signature "BM"
GUInt32 iSize; // Size in bytes of the bitmap file. Should always
// be ignored while reading because of error
// in Windows 3.0 SDK's description of this field
GUInt16 iReserved1; // Reserved, set as 0
GUInt16 iReserved2; // Reserved, set as 0
GUInt32 iOffBits; // Offset of the image from file start in bytes
} BMPFileHeader;
// File header size in bytes:
constexpr int BFH_SIZE = 14;
// Size of sInfoHeader.iSize in bytes
constexpr int SIZE_OF_INFOHEADER_SIZE = 4;
typedef struct
{
GUInt32 iSize; // Size of BMPInfoHeader structure in bytes.
// Should be used to determine start of the
// colour table
GInt32 iWidth; // Image width
GInt32 iHeight; // Image height. If positive, image has bottom left
// origin, if negative --- top left.
GUInt16 iPlanes; // Number of image planes (must be set to 1)
GUInt16 iBitCount; // Number of bits per pixel (1, 4, 8, 16, 24 or 32).
// If 0 then the number of bits per pixel is
// specified or is implied by the JPEG or PNG format.
BMPComprMethod iCompression; // Compression method
GUInt32 iSizeImage; // Size of uncompressed image in bytes. May be 0
// for BMPC_RGB bitmaps. If iCompression is BI_JPEG
// or BI_PNG, iSizeImage indicates the size
// of the JPEG or PNG image buffer.
GInt32 iXPelsPerMeter; // X resolution, pixels per meter (0 if not used)
GInt32 iYPelsPerMeter; // Y resolution, pixels per meter (0 if not used)
GUInt32 iClrUsed; // Size of colour table. If 0, iBitCount should
// be used to calculate this value (1<<iBitCount)
GUInt32 iClrImportant; // Number of important colours. If 0, all
// colours are required
// Fields above should be used for bitmaps, compatible with Windows NT 3.51
// and earlier. Windows 98/Me, Windows 2000/XP introduces additional fields:
GUInt32 iRedMask; // Colour mask that specifies the red component
// of each pixel, valid only if iCompression
// is set to BI_BITFIELDS.
GUInt32 iGreenMask; // The same for green component
GUInt32 iBlueMask; // The same for blue component
// cppcheck-suppress unusedStructMember
GUInt32 iAlphaMask; // Colour mask that specifies the alpha
// component of each pixel.
// cppcheck-suppress unusedStructMember
BMPLCSType iCSType; // Colour space of the DIB.
// cppcheck-suppress unusedStructMember
BMPCIEXYZTriple sEndpoints; // This member is ignored unless the iCSType
// member specifies BMPLT_CALIBRATED_RGB.
// cppcheck-suppress unusedStructMember
GUInt32 iGammaRed; // Toned response curve for red. This member
// is ignored unless color values are calibrated
// RGB values and iCSType is set to
// BMPLT_CALIBRATED_RGB. Specified in 16^16 format.
// cppcheck-suppress unusedStructMember
GUInt32 iGammaGreen; // Toned response curve for green.
// cppcheck-suppress unusedStructMember
GUInt32 iGammaBlue; // Toned response curve for blue.
} BMPInfoHeader;
// Info header size in bytes:
const unsigned int BIH_WIN4SIZE = 40; // for BMPT_WIN4
#if 0 /* Unused */
const unsigned int BIH_WIN5SIZE = 57; // for BMPT_WIN5
#endif
const unsigned int BIH_OS21SIZE = 12; // for BMPT_OS21
const unsigned int BIH_OS22SIZE = 64; // for BMPT_OS22
// We will use plain byte array instead of this structure, but declaration
// provided for reference
typedef struct
{
// cppcheck-suppress unusedStructMember
GByte bBlue;
// cppcheck-suppress unusedStructMember
GByte bGreen;
// cppcheck-suppress unusedStructMember
GByte bRed;
// cppcheck-suppress unusedStructMember
GByte bReserved; // Must be 0
} BMPColorEntry;
/*****************************************************************/
static int countonbits(GUInt32 dw)
{
int r = 0;
for (int x = 0; x < 32; x++)
{
if ((dw & (1U << x)) != 0)
r++;
}
return r;
}
static int findfirstonbit(GUInt32 n)
{
for (int x = 0; x < 32; x++)
{
if ((n & (1U << x)) != 0)
return x;
}
return -1;
}
/************************************************************************/
/* ==================================================================== */
/* BMPDataset */
/* ==================================================================== */
/************************************************************************/
class BMPDataset final : public GDALPamDataset
{
friend class BMPRasterBand;
friend class BMPComprRasterBand;
BMPFileHeader sFileHeader;
BMPInfoHeader sInfoHeader;
int nColorElems;
GByte *pabyColorTable;
GDALColorTable *poColorTable;
double adfGeoTransform[6];
int bGeoTransformValid;
bool m_bNewFile = false;
vsi_l_offset m_nFileSize = 0;
char *pszFilename;
VSILFILE *fp;
protected:
CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
GDALDataType, int, int *, GSpacing nPixelSpace,
GSpacing nLineSpace, GSpacing nBandSpace,
GDALRasterIOExtraArg *psExtraArg) override;
public:
BMPDataset();
~BMPDataset() override;
static int Identify(GDALOpenInfo *);
static GDALDataset *Open(GDALOpenInfo *);
static GDALDataset *Create(const char *pszFilename, int nXSize, int nYSize,
int nBandsIn, GDALDataType eType,
char **papszParamList);
CPLErr GetGeoTransform(double *padfTransform) override;
CPLErr SetGeoTransform(double *) override;
};
/************************************************************************/
/* ==================================================================== */
/* BMPRasterBand */
/* ==================================================================== */
/************************************************************************/
class BMPRasterBand CPL_NON_FINAL : public GDALPamRasterBand
{
friend class BMPDataset;
protected:
GUInt32 nScanSize;
unsigned int iBytesPerPixel;
GByte *pabyScan;
public:
BMPRasterBand(BMPDataset *, int);
~BMPRasterBand() override;
CPLErr IReadBlock(int, int, void *) override;
CPLErr IWriteBlock(int, int, void *) override;
GDALColorInterp GetColorInterpretation() override;
GDALColorTable *GetColorTable() override;
CPLErr SetColorTable(GDALColorTable *) override;
};
/************************************************************************/
/* BMPRasterBand() */
/************************************************************************/
BMPRasterBand::BMPRasterBand(BMPDataset *poDSIn, int nBandIn)
: nScanSize(0), iBytesPerPixel(poDSIn->sInfoHeader.iBitCount / 8),
pabyScan(nullptr)
{
poDS = poDSIn;
nBand = nBandIn;
eDataType = GDT_Byte;
// We will read one scanline per time. Scanlines in BMP aligned at 4-byte
// boundary
nBlockXSize = poDS->GetRasterXSize();
nBlockYSize = 1;
const auto knIntMax = std::numeric_limits<int>::max();
if (nBlockXSize < (knIntMax - 31) / poDSIn->sInfoHeader.iBitCount)
{
nScanSize =
((poDS->GetRasterXSize() * poDSIn->sInfoHeader.iBitCount + 31) &
~31) /
8;
}
else
{
// pabyScan = NULL;
return;
}
#ifdef BMP_DEBUG
CPLDebug("BMP", "Band %d: set nBlockXSize=%d, nBlockYSize=%d, nScanSize=%d",
nBand, nBlockXSize, nBlockYSize, nScanSize);
#endif
pabyScan = static_cast<GByte *>(VSIMalloc(nScanSize));
}
/************************************************************************/
/* ~BMPRasterBand() */
/************************************************************************/
BMPRasterBand::~BMPRasterBand()
{
CPLFree(pabyScan);
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr BMPRasterBand::IReadBlock(int /* nBlockXOff */, int nBlockYOff,
void *pImage)
{
BMPDataset *poGDS = (BMPDataset *)poDS;
vsi_l_offset iScanOffset = 0;
if (poGDS->sInfoHeader.iHeight > 0)
iScanOffset = poGDS->sFileHeader.iOffBits +
(poGDS->GetRasterYSize() - nBlockYOff - 1) *
static_cast<vsi_l_offset>(nScanSize);
else
iScanOffset = poGDS->sFileHeader.iOffBits +
nBlockYOff * static_cast<vsi_l_offset>(nScanSize);
if (VSIFSeekL(poGDS->fp, iScanOffset, SEEK_SET) < 0)
{
// XXX: We will not report error here, because file just may be
// in update state and data for this block will be available later.
if (poGDS->eAccess == GA_Update)
{
memset(pImage, 0, nBlockXSize);
return CE_None;
}
else
{
CPLError(CE_Failure, CPLE_FileIO,
"Can't seek to offset " CPL_FRMT_GUIB
" in input file to read data.",
iScanOffset);
return CE_Failure;
}
}
if (VSIFReadL(pabyScan, 1, nScanSize, poGDS->fp) < nScanSize)
{
// XXX
if (poGDS->eAccess == GA_Update)
{
memset(pImage, 0, nBlockXSize);
return CE_None;
}
else
{
CPLError(CE_Failure, CPLE_FileIO,
"Can't read from offset " CPL_FRMT_GUIB " in input file.",
iScanOffset);
return CE_Failure;
}
}
if (poGDS->sInfoHeader.iBitCount == 24 ||
poGDS->sInfoHeader.iBitCount == 32)
{
GByte *pabyTemp = pabyScan + 3 - nBand;
for (int i = 0; i < nBlockXSize; i++)
{
// Colour triplets in BMP file organized in reverse order:
// blue, green, red. When we have 32-bit BMP the forth byte
// in quadruplet should be discarded as it has no meaning.
// That is why we always use 3 byte count in the following
// pabyTemp index.
((GByte *)pImage)[i] = *pabyTemp;
pabyTemp += iBytesPerPixel;
}
}
else if (poGDS->sInfoHeader.iBitCount == 8)
{
memcpy(pImage, pabyScan, nBlockXSize);
}
else if (poGDS->sInfoHeader.iBitCount == 16)
{
// rcg, oct 7/06: Byteswap if necessary, use int16
// references to file pixels, expand samples to
// 8-bit, support BMPC_BITFIELDS channel mask indicators,
// and generalize band handling.
GUInt16 *pScan16 = (GUInt16 *)pabyScan;
#ifdef CPL_MSB
GDALSwapWords(pScan16, sizeof(GUInt16), nBlockXSize, 0);
#endif
// todo: make these band members and precompute.
int mask[3], shift[3], size[3];
float fTo8bit[3];
if (poGDS->sInfoHeader.iCompression == BMPC_RGB)
{
mask[0] = 0x7c00;
mask[1] = 0x03e0;
mask[2] = 0x001f;
}
else if (poGDS->sInfoHeader.iCompression == BMPC_BITFIELDS)
{
mask[0] = poGDS->sInfoHeader.iRedMask;
mask[1] = poGDS->sInfoHeader.iGreenMask;
mask[2] = poGDS->sInfoHeader.iBlueMask;
}
else
{
CPLError(CE_Failure, CPLE_FileIO, "Unknown 16-bit compression %d.",
poGDS->sInfoHeader.iCompression);
return CE_Failure;
}
for (int i = 0; i < 3; i++)
{
shift[i] = findfirstonbit(mask[i]);
size[i] = countonbits(mask[i]);
if (size[i] > 14 || size[i] == 0)
{
CPLError(CE_Failure, CPLE_FileIO,
"Bad 16-bit channel mask %8x.", mask[i]);
return CE_Failure;
}
fTo8bit[i] = 255.0f / ((1 << size[i]) - 1);
}
for (int i = 0; i < nBlockXSize; i++)
{
((GByte *)pImage)[i] =
(GByte)(0.5f +
fTo8bit[nBand - 1] * ((pScan16[i] & mask[nBand - 1]) >>
shift[nBand - 1]));
#if 0
// original code
switch ( nBand )
{
case 1: // Red
((GByte *) pImage)[i] = pabyScan[i + 1] & 0x1F;
break;
case 2: // Green
((GByte *) pImage)[i] =
((pabyScan[i] & 0x03) << 3) |
((pabyScan[i + 1] & 0xE0) >> 5);
break;
case 3: // Blue
((GByte *) pImage)[i] = (pabyScan[i] & 0x7c) >> 2;
break;
default:
break;
}
#endif // 0
}
}
else if (poGDS->sInfoHeader.iBitCount == 4)
{
GByte *pabyTemp = pabyScan;
for (int i = 0; i < nBlockXSize; i++)
{
// Most significant part of the byte represents leftmost pixel
if (i & 0x01)
((GByte *)pImage)[i] = *pabyTemp++ & 0x0F;
else
((GByte *)pImage)[i] = (*pabyTemp & 0xF0) >> 4;
}
}
else if (poGDS->sInfoHeader.iBitCount == 1)
{
GByte *pabyTemp = pabyScan;
for (int i = 0; i < nBlockXSize; i++)
{
switch (i & 0x7)
{
case 0:
((GByte *)pImage)[i] = (*pabyTemp & 0x80) >> 7;
break;
case 1:
((GByte *)pImage)[i] = (*pabyTemp & 0x40) >> 6;
break;
case 2:
((GByte *)pImage)[i] = (*pabyTemp & 0x20) >> 5;
break;
case 3:
((GByte *)pImage)[i] = (*pabyTemp & 0x10) >> 4;
break;
case 4:
((GByte *)pImage)[i] = (*pabyTemp & 0x08) >> 3;
break;
case 5:
((GByte *)pImage)[i] = (*pabyTemp & 0x04) >> 2;
break;
case 6:
((GByte *)pImage)[i] = (*pabyTemp & 0x02) >> 1;
break;
case 7:
((GByte *)pImage)[i] = *pabyTemp++ & 0x01;
break;
default:
break;
}
}
}
return CE_None;
}
/************************************************************************/
/* IWriteBlock() */
/************************************************************************/
CPLErr BMPRasterBand::IWriteBlock(int nBlockXOff, int nBlockYOff, void *pImage)
{
BMPDataset *poGDS = (BMPDataset *)poDS;
CPLAssert(poGDS != nullptr && nBlockXOff >= 0 && nBlockYOff >= 0 &&
pImage != nullptr);
vsi_l_offset iScanOffset = poGDS->sFileHeader.iOffBits +
(poGDS->GetRasterYSize() - nBlockYOff - 1) *
static_cast<vsi_l_offset>(nScanSize);
if (VSIFSeekL(poGDS->fp, iScanOffset, SEEK_SET) < 0)
{
CPLError(CE_Failure, CPLE_FileIO,
"Can't seek to offset " CPL_FRMT_GUIB
" in output file to write data.\n%s",
iScanOffset, VSIStrerror(errno));
return CE_Failure;
}
if (poGDS->nBands != 1)
{
memset(pabyScan, 0, nScanSize);
VSIFReadL(pabyScan, 1, nScanSize, poGDS->fp);
VSIFSeekL(poGDS->fp, iScanOffset, SEEK_SET);
}
for (int iInPixel = 0, iOutPixel = iBytesPerPixel - nBand;
iInPixel < nBlockXSize; iInPixel++, iOutPixel += poGDS->nBands)
{
pabyScan[iOutPixel] = ((GByte *)pImage)[iInPixel];
}
if (VSIFWriteL(pabyScan, 1, nScanSize, poGDS->fp) < nScanSize)
{
CPLError(CE_Failure, CPLE_FileIO,
"Can't write block with X offset %d and Y offset %d.\n%s",
nBlockXOff, nBlockYOff, VSIStrerror(errno));
return CE_Failure;
}
return CE_None;
}
/************************************************************************/
/* GetColorTable() */
/************************************************************************/
GDALColorTable *BMPRasterBand::GetColorTable()
{
BMPDataset *poGDS = (BMPDataset *)poDS;
return poGDS->poColorTable;
}
/************************************************************************/
/* SetColorTable() */
/************************************************************************/
CPLErr BMPRasterBand::SetColorTable(GDALColorTable *poColorTable)
{
BMPDataset *poGDS = (BMPDataset *)poDS;
if (poColorTable)
{
poGDS->sInfoHeader.iClrUsed = poColorTable->GetColorEntryCount();
if (poGDS->sInfoHeader.iClrUsed < 1 ||
poGDS->sInfoHeader.iClrUsed > (1U << poGDS->sInfoHeader.iBitCount))
return CE_Failure;
VSIFSeekL(poGDS->fp, BFH_SIZE + 32, SEEK_SET);
GUInt32 iULong = CPL_LSBWORD32(poGDS->sInfoHeader.iClrUsed);
VSIFWriteL(&iULong, 4, 1, poGDS->fp);
poGDS->pabyColorTable = (GByte *)CPLRealloc(
poGDS->pabyColorTable, static_cast<size_t>(poGDS->nColorElems) *
poGDS->sInfoHeader.iClrUsed);
if (!poGDS->pabyColorTable)
return CE_Failure;
for (unsigned int i = 0; i < poGDS->sInfoHeader.iClrUsed; i++)
{
GDALColorEntry oEntry;
poColorTable->GetColorEntryAsRGB(i, &oEntry);
poGDS->pabyColorTable[i * poGDS->nColorElems + 3] = 0;
poGDS->pabyColorTable[i * poGDS->nColorElems + 2] =
(GByte)oEntry.c1; // Red
poGDS->pabyColorTable[i * poGDS->nColorElems + 1] =
(GByte)oEntry.c2; // Green
poGDS->pabyColorTable[i * poGDS->nColorElems] =
(GByte)oEntry.c3; // Blue
}
VSIFSeekL(poGDS->fp, BFH_SIZE + poGDS->sInfoHeader.iSize, SEEK_SET);
if (VSIFWriteL(poGDS->pabyColorTable, 1,
static_cast<size_t>(poGDS->nColorElems) *
poGDS->sInfoHeader.iClrUsed,
poGDS->fp) < static_cast<size_t>(poGDS->nColorElems) *
poGDS->sInfoHeader.iClrUsed)
{
return CE_Failure;
}
}
else
return CE_Failure;
return CE_None;
}
/************************************************************************/
/* GetColorInterpretation() */
/************************************************************************/
GDALColorInterp BMPRasterBand::GetColorInterpretation()
{
BMPDataset *poGDS = (BMPDataset *)poDS;
if (poGDS->sInfoHeader.iBitCount == 24 ||
poGDS->sInfoHeader.iBitCount == 32 ||
poGDS->sInfoHeader.iBitCount == 16)
{
if (nBand == 1)
return GCI_RedBand;
else if (nBand == 2)
return GCI_GreenBand;
else if (nBand == 3)
return GCI_BlueBand;
else
return GCI_Undefined;
}
else
{
return GCI_PaletteIndex;
}
}
/************************************************************************/
/* ==================================================================== */
/* BMPComprRasterBand */
/* ==================================================================== */
/************************************************************************/
class BMPComprRasterBand final : public BMPRasterBand
{
friend class BMPDataset;
GByte *pabyComprBuf;
GByte *pabyUncomprBuf;
public:
BMPComprRasterBand(BMPDataset *, int);
~BMPComprRasterBand() override;
CPLErr IReadBlock(int, int, void *) override;
// virtual CPLErr IWriteBlock( int, int, void * );
};
/************************************************************************/
/* BMPComprRasterBand() */
/************************************************************************/
BMPComprRasterBand::BMPComprRasterBand(BMPDataset *poDSIn, int nBandIn)
: BMPRasterBand(poDSIn, nBandIn), pabyComprBuf(nullptr),
pabyUncomprBuf(nullptr)
{
/* TODO: it might be interesting to avoid uncompressing the whole data */
/* in a single pass, especially if nXSize * nYSize is big */
/* We could read incrementally one row at a time */
const auto knIntMax = std::numeric_limits<int>::max();
if (poDS->GetRasterXSize() > knIntMax / poDS->GetRasterYSize())
{
CPLError(CE_Failure, CPLE_NotSupported, "Too big dimensions : %d x %d",
poDS->GetRasterXSize(), poDS->GetRasterYSize());
return;
}
if (poDSIn->m_nFileSize <= poDSIn->sFileHeader.iOffBits ||
poDSIn->m_nFileSize - poDSIn->sFileHeader.iOffBits > knIntMax)
{
CPLError(CE_Failure, CPLE_NotSupported, "Invalid header");
return;
}
const GUInt32 iComprSize = static_cast<GUInt32>(
poDSIn->m_nFileSize - poDSIn->sFileHeader.iOffBits);
const GUInt32 iUncomprSize =
poDS->GetRasterXSize() * poDS->GetRasterYSize();
#ifdef DEBUG
CPLDebug("BMP", "RLE compression detected.");
CPLDebug("BMP",
"Size of compressed buffer %ld bytes,"
" size of uncompressed buffer %ld bytes.",
(long)iComprSize, (long)iUncomprSize);
#endif
pabyComprBuf = (GByte *)VSIMalloc(iComprSize);
pabyUncomprBuf = (GByte *)VSIMalloc(iUncomprSize);
if (pabyComprBuf == nullptr || pabyUncomprBuf == nullptr)
{
CPLFree(pabyComprBuf);
pabyComprBuf = nullptr;
CPLFree(pabyUncomprBuf);
pabyUncomprBuf = nullptr;
return;
}
if (VSIFSeekL(poDSIn->fp, poDSIn->sFileHeader.iOffBits, SEEK_SET) != 0 ||
VSIFReadL(pabyComprBuf, 1, iComprSize, poDSIn->fp) < iComprSize)
{
CPLError(CE_Failure, CPLE_FileIO,
"Can't read from offset %ld in input file.",
(long)poDSIn->sFileHeader.iOffBits);
CPLFree(pabyComprBuf);
pabyComprBuf = nullptr;
CPLFree(pabyUncomprBuf);
pabyUncomprBuf = nullptr;
return;
}
unsigned int i = 0;
unsigned int j = 0;
if (poDSIn->sInfoHeader.iBitCount == 8) // RLE8
{
while (i < iComprSize)
{
if (pabyComprBuf[i])
{
unsigned int iLength = pabyComprBuf[i++];
if (j == iUncomprSize)
break;
while (iLength > 0 && j < iUncomprSize && i < iComprSize)
{
pabyUncomprBuf[j++] = pabyComprBuf[i];
iLength--;
}
i++;
}
else
{
i++;
if (i == iComprSize)
break;
if (pabyComprBuf[i] == 0) // Next scanline
{
i++;
}
else if (pabyComprBuf[i] == 1) // End of image
{
break;
}
else if (pabyComprBuf[i] == 2) // Move to...
{
if (j == iUncomprSize)
break;
i++;
if (i < iComprSize - 1)
{
if (pabyComprBuf[i + 1] >
knIntMax / poDS->GetRasterXSize() ||
static_cast<int>(pabyComprBuf[i + 1]) *
poDS->GetRasterXSize() >
knIntMax -
static_cast<int>(j + pabyComprBuf[i]))
break;
j += pabyComprBuf[i] +
pabyComprBuf[i + 1] * poDS->GetRasterXSize();
i += 2;
}
else
break;
}
else // Absolute mode
{
CPLAssert(i < iComprSize);
unsigned int iLength = pabyComprBuf[i++];
if (j == iUncomprSize)
break;
for (unsigned k = 0;
k < iLength && j < iUncomprSize && i < iComprSize; k++)
pabyUncomprBuf[j++] = pabyComprBuf[i++];
if (i & 0x01)
i++;
}
}
}
}
else // RLE4
{
while (i < iComprSize)
{
if (pabyComprBuf[i])
{
unsigned int iLength = pabyComprBuf[i++];
if (j == iUncomprSize)
break;
while (iLength > 0 && j < iUncomprSize && i < iComprSize)
{
if (iLength & 0x01)
pabyUncomprBuf[j++] = (pabyComprBuf[i] & 0xF0) >> 4;
else
pabyUncomprBuf[j++] = pabyComprBuf[i] & 0x0F;
iLength--;
}
i++;
}
else
{
i++;
if (i == iComprSize)
break;
if (pabyComprBuf[i] == 0) // Next scanline
{
i++;
}
else if (pabyComprBuf[i] == 1) // End of image
{
break;
}
else if (pabyComprBuf[i] == 2) // Move to...
{
if (j == iUncomprSize)
break;
i++;
if (i < iComprSize - 1)
{
if (pabyComprBuf[i + 1] >
knIntMax / poDS->GetRasterXSize() ||
static_cast<int>(pabyComprBuf[i + 1]) *
poDS->GetRasterXSize() >
knIntMax -
static_cast<int>(j + pabyComprBuf[i]))
break;
j += pabyComprBuf[i] +
pabyComprBuf[i + 1] * poDS->GetRasterXSize();
i += 2;
}
else
break;
}
else // Absolute mode
{
CPLAssert(i < iComprSize);
unsigned int iLength = pabyComprBuf[i++];
if (j == iUncomprSize)
break;
for (unsigned k = 0;
k < iLength && j < iUncomprSize && i < iComprSize; k++)
{
if (k & 0x01)
pabyUncomprBuf[j++] = pabyComprBuf[i++] & 0x0F;
else
pabyUncomprBuf[j++] = (pabyComprBuf[i] & 0xF0) >> 4;
}
if (i & 0x01)
i++;
}
}
}
}
/* Validate that we have read all compressed data (we tolerate missing */
/* end of image marker) and that we have filled all uncompressed data */
if (j < iUncomprSize || (i + 1 != iComprSize && i + 2 != iComprSize))
{
CPLFree(pabyUncomprBuf);
pabyUncomprBuf = nullptr;
}
// rcg, release compressed buffer here.
CPLFree(pabyComprBuf);
pabyComprBuf = nullptr;
}
/************************************************************************/
/* ~BMPComprRasterBand() */
/************************************************************************/
BMPComprRasterBand::~BMPComprRasterBand()
{
CPLFree(pabyComprBuf);
CPLFree(pabyUncomprBuf);
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr BMPComprRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
void *pImage)
{
memcpy(pImage,
pabyUncomprBuf + (poDS->GetRasterYSize() - nBlockYOff - 1) *
poDS->GetRasterXSize(),
nBlockXSize);
return CE_None;
}
/************************************************************************/
/* BMPDataset() */
/************************************************************************/
BMPDataset::BMPDataset()
: nColorElems(0), pabyColorTable(nullptr), poColorTable(nullptr),
bGeoTransformValid(FALSE), pszFilename(nullptr), fp(nullptr)
{
nBands = 0;
memset(&sFileHeader, 0, sizeof(sFileHeader));
memset(&sInfoHeader, 0, sizeof(sInfoHeader));
adfGeoTransform[0] = 0.0;
adfGeoTransform[1] = 1.0;
adfGeoTransform[2] = 0.0;
adfGeoTransform[3] = 0.0;
adfGeoTransform[4] = 0.0;
adfGeoTransform[5] = 1.0;
}
/************************************************************************/
/* ~BMPDataset() */
/************************************************************************/
BMPDataset::~BMPDataset()
{
FlushCache(true);
if (m_bNewFile && fp)
{
// Extend the file with zeroes if needed
VSIFSeekL(fp, 0, SEEK_END);
if (VSIFTellL(fp) < m_nFileSize)
{
VSIFTruncateL(fp, m_nFileSize);
}
}
CPLFree(pabyColorTable);
if (poColorTable)
delete poColorTable;
CPLFree(pszFilename);
if (fp)
VSIFCloseL(fp);
}
/************************************************************************/
/* GetGeoTransform() */
/************************************************************************/
CPLErr BMPDataset::GetGeoTransform(double *padfTransform)
{
if (bGeoTransformValid)
{
memcpy(padfTransform, adfGeoTransform, sizeof(adfGeoTransform[0]) * 6);