File: itkBMPImageIO.cxx

package info (click to toggle)
insighttoolkit 3.6.0-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 94,956 kB
  • ctags: 74,981
  • sloc: cpp: 355,621; ansic: 195,070; fortran: 28,713; python: 3,802; tcl: 1,996; sh: 1,175; java: 583; makefile: 415; csh: 184; perl: 175
file content (967 lines) | stat: -rw-r--r-- 25,442 bytes parent folder | download
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
/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: itkBMPImageIO.cxx,v $
  Language:  C++
  Date:      $Date: 2008-03-10 23:59:06 $
  Version:   $Revision: 1.26 $  

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even 
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkBMPImageIO.h"
#include "itkExceptionObject.h"
#include "itkByteSwapper.h"
#include "itkRGBPixel.h"
#include "itkRGBAPixel.h"
#include <itksys/SystemTools.hxx>
#include <iostream>
#include <list>
#include <string>
#include <math.h>

namespace itk
{

/** Constructor */
BMPImageIO::BMPImageIO()
{
  m_ByteOrder = BigEndian;
  m_BitMapOffset = 0;
  this->SetNumberOfDimensions(2);
  m_PixelType = SCALAR;
  m_ComponentType = UCHAR;
  m_Spacing[0] = 1.0;
  m_Spacing[1] = 1.0;
  
  m_Origin[0] = 0.0;
  m_Origin[1] = 0.0;
  m_FileLowerLeft = 0;
  m_Depth = 8;
  m_Allow8BitBMP = true;
  m_NumberOfColors = 0;
  m_BMPCompression = 0;
  m_BMPDataSize = 0;
}


/** Destructor */
BMPImageIO::~BMPImageIO()
{
}


bool BMPImageIO::CanReadFile( const char* filename ) 
{ 
  // First check the filename extension
  std::string fname = filename;
  if ( fname == "" )
    {
    itkDebugMacro(<< "No filename specified.");
    }

  bool extensionFound = false;
  std::string::size_type BMPPos = fname.rfind(".bmp");
  if ((BMPPos != std::string::npos)
      && (BMPPos == fname.length() - 4))
    {
    extensionFound = true;
    }

  BMPPos = fname.rfind(".BMP");
  if ((BMPPos != std::string::npos)
      && (BMPPos == fname.length() - 4))
    {
    extensionFound = true;
    }

  if( !extensionFound )
    {
    itkDebugMacro(<<"The filename extension is not recognized");
    return false;
    }

  // Now check the content
  std::ifstream inputStream;
  inputStream.open( filename, std::ios::in | std::ios::binary );
  if( inputStream.fail() )
    {
    return false;
    }
 
  char magic_number1, magic_number2;
  inputStream.read((char*)&magic_number1,sizeof(char));
  inputStream.read((char*)&magic_number2,sizeof(char));

  if ((magic_number1 != 'B')||(magic_number2 != 'M'))
    {
    std::cerr << "BMPImageIO : Magic Number Fails = " << magic_number1 << " : " << magic_number2 << std::endl;
    inputStream.close();
    return false;
    }

  long tmp;
  long infoSize;
  int  iinfoSize;  // in case we are on a 64bit machine
  int  itmp;       // in case we are on a 64bit machine

  // get the size of the file
  ::size_t sizeLong = sizeof(long);
  if (sizeLong == 4)
    {
    inputStream.read((char*)&tmp,4);
    // skip 4 bytes
    inputStream.read((char*)&tmp,4);
    // read the offset
    inputStream.read((char*)&tmp,4);
    }
  else
    {
    inputStream.read((char*)&itmp,4);
    // skip 4 bytes
    inputStream.read((char*)&itmp,4);
    // read the offset
    inputStream.read((char*)&itmp,4);
    }

  // get size of header
  if (sizeLong == 4)   // if we are on a 32 bit machine
    {
    inputStream.read((char*)&infoSize,sizeof(long));
    ByteSwapper<long>::SwapFromSystemToLittleEndian(&infoSize);
    // error checking
    if ((infoSize != 40)&&(infoSize != 12))
      {
      inputStream.close();
      return false;
      }
    }
  else    // else we are on a 64bit machine
    {
    inputStream.read((char*)&iinfoSize,4);
    ByteSwapper<int>::SwapFromSystemToLittleEndian(&iinfoSize);
    infoSize = iinfoSize;
    
    // error checking
    if ((infoSize != 40)&&(infoSize != 12))
      {
      inputStream.close();
      return false;
      }
    }

  inputStream.close();
  return true;

}
  
bool BMPImageIO::CanWriteFile( const char * name )
{
  std::string filename = name;
  if ( filename == "" )
    {
    itkDebugMacro(<< "No filename specified.");
    }

  bool extensionFound = false;
  std::string::size_type BMPPos = filename.rfind(".bmp");
  if ((BMPPos != std::string::npos)
      && (BMPPos == filename.length() - 4))
    {
    extensionFound = true;
    }
  
  BMPPos = filename.rfind(".BMP");
  if ((BMPPos != std::string::npos)
      && (BMPPos == filename.length() - 4))
    {
    extensionFound = true;
    }

  if( !extensionFound )
    {
    itkDebugMacro(<<"The filename extension is not recognized");
    return false;
    }

  if( extensionFound )
    {
    return true;
    }
  return false;
}
 
void BMPImageIO::Read(void* buffer)
{
  char * p = static_cast<char *>(buffer);
  unsigned long l=0;
  unsigned long step = this->GetNumberOfComponents();
  long streamRead = m_Dimensions[0]*m_Depth/8;

  m_Ifstream.open( m_FileName.c_str(), std::ios::in | std::ios::binary );

  long paddedStreamRead = streamRead;
  if( streamRead % 4 )
    {
    paddedStreamRead = ( ( streamRead / 4 ) + 1 ) * 4;
    }

  char* value = new char[paddedStreamRead+1];
  if (m_FileLowerLeft)
    {
    // If the file is RLE compressed
    if(m_BMPCompression == 1 && this->GetNumberOfComponents() == 3)
      {
      delete [] value;
      value = new char[m_BMPDataSize+1];
      m_Ifstream.seekg(m_BitMapOffset,std::ios::beg);
      m_Ifstream.read((char *)value, m_BMPDataSize);
 
      unsigned int posLine=0;
      unsigned int line = m_Dimensions[1]-1;
      for(unsigned int i=0;i<m_BMPDataSize;i++)
        {
        unsigned long n = value[i];
        i++;
        unsigned char valpix = value[i];
        for(unsigned long j=0;j<n;j++)
          {
          RGBPixelType rbg;
          if(valpix<m_ColorPalette.size())
            {
            rbg = m_ColorPalette[valpix];
            }
          else
            {
            rbg.SetRed(0);
            rbg.SetGreen(0);
            rbg.SetBlue(0);
            }
          l=3*(line*m_Dimensions[0]+posLine);
          p[l]=rbg.GetBlue();
          p[l+1]=rbg.GetGreen();
          p[l+2]=rbg.GetRed();
          posLine++;
          if(posLine == m_Dimensions[0])
            {
            line--;
            posLine=0;
            }
          }
        }
      }
    else
      {
      for(unsigned int id=0;id<m_Dimensions[1];id++)
        {
        m_Ifstream.seekg(m_BitMapOffset + paddedStreamRead*(m_Dimensions[1] - id - 1),std::ios::beg);
        m_Ifstream.read((char *)value, paddedStreamRead);

        for(long i=0;i<streamRead;i++)
          {
          if(this->GetNumberOfComponents() == 1)
            {
            p[l++]=value[i];
            }
          else
            {
            if(m_NumberOfColors == 0)
              {
              if(this->GetNumberOfComponents() == 3 )
                {
                p[l++]=value[i+2];
                p[l++]=value[i+1];
                p[l++]=value[i];
                }
              if(this->GetNumberOfComponents() == 4 )
                {
                p[l++]=value[i+3];
                p[l++]=value[i+2];
                p[l++]=value[i+1];
                p[l++]=value[i];
                }
              i += step-1;
              }
            else
              {
              unsigned char val = value[i];
              RGBPixelType rbg;
              if(val<m_ColorPalette.size())
                {
                rbg = m_ColorPalette[val];
                }
              else
                {
                rbg.SetRed(0);
                rbg.SetGreen(0);
                rbg.SetBlue(0);
                }
              p[l++]=rbg.GetBlue();
              p[l++]=rbg.GetGreen();
              p[l++]=rbg.GetRed();
              }
            }
          }
        }
      }
    }
  else
    {
    m_Ifstream.seekg(m_BitMapOffset,std::ios::beg);
    for(unsigned int id=0;id<m_Dimensions[1];id++)
      {
      m_Ifstream.read((char *)value, streamRead);

      for(long i=0;i<streamRead;i+=step)
        { 
        if(this->GetNumberOfComponents() == 1)
          {
          p[l++]=value[i];
          }
        else
          {
          p[l++]=value[i+2];
          p[l++]=value[i+1];
          p[l++]=value[i];
          }
        }
      }
    }
  delete []value;
  m_Ifstream.close();
}

/** 
 *  Read Information about the BMP file
 *  and put the cursor of the stream just before the first data pixel
 */
void BMPImageIO::ReadImageInformation()
{
  int xsize, ysize;
  long tmp;
  short stmp;
  long infoSize;
  int  iinfoSize;  // in case we are on a 64bit machine
  int  itmp;       // in case we are on a 64bit machine

  // Now check the content
  m_Ifstream.open( m_FileName.c_str(), std::ios::in | std::ios::binary );
  if( m_Ifstream.fail() )
    {
    itkExceptionMacro("BMPImageIO could not open file: "
                      << this->GetFileName() << " for reading."
                      << std::endl
                      << "Reason: "
                      << itksys::SystemTools::GetLastSystemError());
    }
 
  char magic_number1, magic_number2;
  m_Ifstream.read((char*)&magic_number1,sizeof(char));
  m_Ifstream.read((char*)&magic_number2,sizeof(char));

  if ((magic_number1 != 'B')||(magic_number2 != 'M'))
    {
    m_Ifstream.close();
    itkExceptionMacro( "BMPImageIO : Magic Number Fails = " << magic_number1 << " : " << magic_number2 );
    return;
    }

  // get the size of the file
  ::size_t sizeLong = sizeof(long);
  if (sizeLong == 4)
    {
    m_Ifstream.read((char*)&tmp,4);
    // skip 4 bytes
    m_Ifstream.read((char*)&tmp,4);
    // read the offset
    m_Ifstream.read((char*)&tmp,4);
    m_BitMapOffset = tmp;
    ByteSwapper<long>::SwapFromSystemToLittleEndian(&m_BitMapOffset);
    }
  else
    {
    m_Ifstream.read((char*)&itmp,4);
    // skip 4 bytes
    m_Ifstream.read((char*)&itmp,4);
    // read the offset
    m_Ifstream.read((char*)&itmp,4);
    ByteSwapper<int>::SwapFromSystemToLittleEndian(&itmp);
    m_BitMapOffset = static_cast<long>(itmp);
    }

  // get size of header
  if (sizeLong == 4)   // if we are on a 32 bit machine
    {
    m_Ifstream.read((char*)&infoSize,4);
    ByteSwapper<long>::SwapFromSystemToLittleEndian(&infoSize);
                       
    // error checking
    if ((infoSize != 40)&&(infoSize != 12))
      {
      itkExceptionMacro(<<"Unknown file type! " << m_FileName.c_str() 
                        <<" is not a Windows BMP file!");
      m_Ifstream.close();
      return;
      }
  
    // there are two different types of BMP files
    if (infoSize == 40)
      {
      // now get the dimensions
      m_Ifstream.read((char*)&xsize,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&xsize);
      m_Ifstream.read((char*)&ysize,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&ysize);
      }
    else
      {
      m_Ifstream.read((char*)&stmp,sizeof(short));
      ByteSwapper<short>::SwapFromSystemToLittleEndian(&stmp);
      xsize = stmp;
      m_Ifstream.read((char*)&stmp,sizeof(short));
      ByteSwapper<short>::SwapFromSystemToLittleEndian(&stmp);
      ysize = stmp;
      }
    }
  else // else we are on a 64bit machine
    {
    m_Ifstream.read((char*)&iinfoSize,sizeof(int));
    ByteSwapper<int>::SwapFromSystemToLittleEndian(&iinfoSize);
    
    infoSize = iinfoSize;
    
    // error checking
    if ((infoSize != 40)&&(infoSize != 12))
      {
      itkExceptionMacro(<<"Unknown file type! " << m_FileName.c_str() 
                        <<" is not a Windows BMP file!");
      m_Ifstream.close();
      return;
      }
  
    // there are two different types of BMP files
    if (infoSize == 40)
      {
      // now get the dimensions
      m_Ifstream.read((char*)&xsize,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&xsize);
      m_Ifstream.read((char*)&ysize,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&ysize);
      }
    else
      {
      stmp =0;
      m_Ifstream.read((char*)&stmp,2);
      ByteSwapper<short>::SwapFromSystemToLittleEndian(&stmp);
      xsize = stmp;
      m_Ifstream.read((char*)&stmp,2);
      ByteSwapper<short>::SwapFromSystemToLittleEndian(&stmp);
      ysize = stmp;
      }
    }
  
  this->SetNumberOfDimensions(2);
  m_Dimensions[0] = xsize;
  m_Dimensions[1] = ysize;
  
  // is corner in upper left or lower left
  if (ysize < 0)
    {
    ysize = ysize*-1;
    m_FileLowerLeft = 0;
    }
  else
    {
    m_FileLowerLeft = 1;
    }
    
  // ignore planes
  m_Ifstream.read((char*)&stmp,2);
  // read depth
  m_Ifstream.read((char*)&m_Depth,2);
  ByteSwapper<short>::SwapFromSystemToLittleEndian(&m_Depth);

  if ((m_Depth != 8)&&(m_Depth != 24)&&(m_Depth != 32))
    {
    m_Ifstream.close();
    itkExceptionMacro( "Only BMP depths of (8,24,32) are supported. Not " << m_Depth );
    return;
    }
  
  if (infoSize == 40)
    {
    if (sizeLong == 4)
      {
      // Compression
      m_Ifstream.read((char*)&m_BMPCompression,4);
      ByteSwapper<long>::SwapFromSystemToLittleEndian(&m_BMPCompression);
      // Image Data Size
      m_Ifstream.read((char*)&m_BMPDataSize,4);
      ByteSwapper<unsigned long>::SwapFromSystemToLittleEndian(&m_BMPDataSize);
      // Horizontal Resolution
      m_Ifstream.read((char*)&tmp,4);
      // Vertical Resolution
      m_Ifstream.read((char*)&tmp,4);
      // Number of colors
      m_Ifstream.read((char*)&tmp,4);
      m_NumberOfColors = tmp;
      // Number of important colors
      m_Ifstream.read((char*)&tmp,4);
      }
    else
      {
      // Compression
      m_Ifstream.read((char*)&itmp,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&itmp);
      m_BMPCompression = static_cast<long>(itmp);
      // Image Data Size
      m_Ifstream.read((char*)&itmp,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&itmp);
      m_BMPDataSize = static_cast<unsigned long>(itmp);
      // Horizontal Resolution
      m_Ifstream.read((char*)&itmp,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&itmp);
      // Vertical Resolution
      m_Ifstream.read((char*)&itmp,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&itmp);
      // Number of colors
      m_Ifstream.read((char*)&itmp,4);
      ByteSwapper<int>::SwapFromSystemToLittleEndian(&itmp);
      m_NumberOfColors = static_cast<unsigned short>(itmp);
      // Number of important colors
      m_Ifstream.read((char*)&itmp,4);
      }
    }

  // Read the color palette
  unsigned char uctmp;
  for(unsigned long i=0;i<m_NumberOfColors;i++)
    {
    RGBPixelType p;
    m_Ifstream.read((char*)&uctmp,1);
    p.SetRed(uctmp);
    m_Ifstream.read((char*)&uctmp,1);
    p.SetGreen(uctmp);
    m_Ifstream.read((char*)&uctmp,1);
    p.SetBlue(uctmp);
    m_Ifstream.read((char*)&tmp,1);
    m_ColorPalette.push_back(p);
    }

  switch( m_Depth )
    {
    case 8:
      {
      if( m_Allow8BitBMP )
        {
        this->SetNumberOfComponents(1);
        m_PixelType = SCALAR;
        }
      break;
      }
    case 24:
      {
      this->SetNumberOfComponents(3);
      m_PixelType = RGB;
      break;
      }
    case 32:
      {
      this->SetNumberOfComponents(4);
      m_PixelType = RGBA;
      break;
      }
    }

  m_Ifstream.close();
}


void 
BMPImageIO
::SwapBytesIfNecessary( void* buffer, unsigned long numberOfPixels )
{
  switch(m_ComponentType)
    {
    case CHAR:
      {
      if ( m_ByteOrder == LittleEndian )
        {
        ByteSwapper<char>::SwapRangeFromSystemToLittleEndian(
          (char*)buffer, numberOfPixels );
        }
      else if ( m_ByteOrder == BigEndian )
        {
        ByteSwapper<char>::SwapRangeFromSystemToBigEndian(
          (char *)buffer, numberOfPixels );
        }
      break;
      }
    case UCHAR:
      {
      if ( m_ByteOrder == LittleEndian )
        {
        ByteSwapper<unsigned char>::SwapRangeFromSystemToLittleEndian(
          (unsigned char*)buffer, numberOfPixels );
        }
      else if ( m_ByteOrder == BigEndian )
        {
        ByteSwapper<unsigned char>::SwapRangeFromSystemToBigEndian(
          (unsigned char *)buffer, numberOfPixels );
        }
      break;
      }
    case SHORT:
      {
      if ( m_ByteOrder == LittleEndian )
        {
        ByteSwapper<short>::SwapRangeFromSystemToLittleEndian(
          (short*)buffer, numberOfPixels );
        }
      else if ( m_ByteOrder == BigEndian )
        {
        ByteSwapper<short>::SwapRangeFromSystemToBigEndian(
          (short *)buffer, numberOfPixels );
        }
      break;
      }
    case USHORT:
      {
      if ( m_ByteOrder == LittleEndian )
        {
        ByteSwapper<unsigned short>::SwapRangeFromSystemToLittleEndian(
          (unsigned short*)buffer, numberOfPixels );
        }
      else if ( m_ByteOrder == BigEndian )
        {
        ByteSwapper<unsigned short>::SwapRangeFromSystemToBigEndian(
          (unsigned short *)buffer, numberOfPixels );
        }
      break; 
      }
    default:
      itkExceptionMacro(<< "Pixel Type Unknown");
    }
}


void 
BMPImageIO
::Write32BitsInteger( unsigned int value )
{
  char tmp;
  tmp = value%256;
  m_Ofstream.write(&tmp,sizeof(char));
  tmp = (value%65536L)/256;
  m_Ofstream.write(&tmp,sizeof(char));
  tmp = (value/65536L)%256;
  m_Ofstream.write(&tmp,sizeof(char));
  tmp = (value/65536L)/256;
  m_Ofstream.write(&tmp,sizeof(char));
}

void 
BMPImageIO
::Write16BitsInteger( unsigned short value )
{
  char tmp;
  tmp = value%256;
  m_Ofstream.write(&tmp,sizeof(char));
  tmp = (value%65536L)/256;
  m_Ofstream.write(&tmp,sizeof(char));
}

void 
BMPImageIO
::WriteImageInformation(void)
{
  
}

/** The write function is not implemented */
void 
BMPImageIO
::Write( const void* buffer) 
{
 
  unsigned int nDims = this->GetNumberOfDimensions();

  if(nDims != 2)
    {
    itkExceptionMacro(<< "BMPImageIO cannot write images with a dimension != 2");
    }

  if(this->GetComponentType() != UCHAR)
    {
    itkExceptionMacro(<<"BMPImageIO supports unsigned char only");
    }
  if( (this->m_NumberOfComponents != 1) && 
      (this->m_NumberOfComponents != 3) && 
      (this->m_NumberOfComponents != 4) )
    {
    itkExceptionMacro(<<"BMPImageIO supports 1,3 or 4 components only");
    }
  

#ifdef __sgi
  // Create the file. This is required on some older sgi's
  std::ofstream tFile(m_FileName.c_str(),std::ios::out);
  tFile.close();
#endif

  m_Ofstream.open(m_FileName.c_str(), std::ios::binary | std::ios::out);
  if( m_Ofstream.fail() )
    {
    itkExceptionMacro(<< "File: " << this->GetFileName() << " cannot be written."
                      << std::endl
                      << "Reason: "
                      << itksys::SystemTools::GetLastSystemError());
    }

  //
  //
  // A BMP file has four sections:
  //
  // * BMP Header                         14 bytes
  // * Bitmap Information (DIB header)    40 bytes (Windows V3) 
  // * Color Palette
  // * Bitmap Data
  //
  // For more details:
  //
  //             http://en.wikipedia.org/wiki/BMP_file_format
  //
  //
  
  // Write the BMP header
  //
  // Header structure is represented by first a 14 byte field, then the bitmap 
  // info header. 
  // 
  // The 14 byte field:
  // 
  // Offset Length Description
  // 
  //   0      2    Contain the string, "BM", (Hex: 42 4D)
  //   2      4    The length of the entire file.  
  //   6      2    Reserved for application data. Usually zero.
  //   8      2    Reserved for application data. Usually zero.
  //  10      4    Provides an offset from the start of the file 
  //               to the first byte of image sample data. This 
  //               is normally 54 bytes (Hex: 36)
  //
  char tmp = 66;
  m_Ofstream.write(&tmp,sizeof(char));
  tmp = 77;
  m_Ofstream.write(&tmp,sizeof(char));

  const unsigned int bpp = this->GetNumberOfComponents(); 
  long bytesPerRow = m_Dimensions[0]*bpp;  
  if ( bytesPerRow % 4 )
    {
    bytesPerRow = ( ( bytesPerRow / 4 ) + 1 ) * 4;
    }
  const unsigned long paddedBytes = bytesPerRow - (m_Dimensions[0]*bpp);

  const unsigned int rawImageDataSize = ( bytesPerRow * m_Dimensions[1]);
  unsigned int fileSize = ( rawImageDataSize ) + 54;
  if( bpp == 1 ) 
    {
    fileSize += 1024; // need colour LUT
    }
  this->Write32BitsInteger( fileSize );

  const unsigned short applicationReservedValue = 0;
  this->Write16BitsInteger( applicationReservedValue );
  this->Write16BitsInteger( applicationReservedValue );

  unsigned int offsetToBinaryDataStart = 54;
  if( bpp == 1 ) // more space is needed for the LUT
    {
    offsetToBinaryDataStart += 1024;
    }
  this->Write32BitsInteger( offsetToBinaryDataStart );
  //  
  // End of BMP header, 14 bytes written so far
  //
  
 
  //
  // Write the DIB header
  //
  // Offset Length Description
  // 
  //  14      4    Size of the header (40 bytes)(Hex: 28)
  //
  //
  //  Color Palette
  //
  //  If the bit_count is 1, 4 or 8, the structure must be followed by a colour
  //  lookup table, with 4 bytes per entry, the first 3 of which identify the
  //  blue, green and red intensities, respectively.
  //
  //  Finally the pixel data
  //
  const unsigned int bitmapHeaderSize = 40;
  this->Write32BitsInteger( bitmapHeaderSize );
  
  // image width
  this->Write32BitsInteger( m_Dimensions[0] );
  
  // image height -ve means top to bottom
  this->Write32BitsInteger( m_Dimensions[1] );
  
  // Set `planes'=1 (mandatory)
  const unsigned short numberOfColorPlanes = 1;
  this->Write16BitsInteger( numberOfColorPlanes );

  // Set bits per pixel.  
  unsigned short numberOfBitsPerPixel = 0;
  switch( bpp )
    {
    case 4:
      numberOfBitsPerPixel = 32;
      break;
    case 3:
      numberOfBitsPerPixel = 24;
      break;
    case 1:
      numberOfBitsPerPixel = 8;
      break;
    default:
      itkExceptionMacro(<< "Number of components not supported.");
    }
  this->Write16BitsInteger( numberOfBitsPerPixel );

  const unsigned int compressionMethod = 0;
  this->Write32BitsInteger( compressionMethod );
  this->Write32BitsInteger( rawImageDataSize );

  // Assuming spacing is in millimeters, 
  // the resolution is set here in pixel per meter.
  // The specification calls for a signed integer, but
  // here we force it to be an unsigned integer to avoid
  // dealing with directions in a subterraneous way.
  const unsigned int horizontalResolution = 
    static_cast<unsigned int>( vnl_math_rnd( 1000.0 / m_Spacing[0] ) );
  const unsigned int verticalResolution =
    static_cast<unsigned int>( vnl_math_rnd( 1000.0 / m_Spacing[1] ) );

  this->Write32BitsInteger( horizontalResolution );
  this->Write32BitsInteger( verticalResolution );

  // zero here defaults to 2^n colors in the palette
  const unsigned int numberOfColorsInPalette = 0;
  this->Write32BitsInteger( numberOfColorsInPalette );

  // zero here indicates that all colors in the palette are important.
  const unsigned int numberOfImportantColorsInPalette = 0; 
  this->Write32BitsInteger( numberOfImportantColorsInPalette );
  //  
  // End of DIB header, 54 bytes written so far
  //
  

  //
  // Write down colour LUT
  //
  // only when using 1 byte per pixel
  //
  if (bpp == 1)
    {
    for (unsigned int n=0; n < 256; n++)
      { 
      char tmp2 = static_cast< unsigned char >( n );
      m_Ofstream.write(&tmp2,sizeof(char));
      m_Ofstream.write(&tmp2,sizeof(char));
      m_Ofstream.write(&tmp2,sizeof(char));
      m_Ofstream.write(&tmp,sizeof(char));
      }
    }


  //
  // Write down the raw binary pixel data
  //
  unsigned int i;
  for (unsigned int h = 0; h < m_Dimensions[1]; h++)
    {  
    const char paddingValue = 0;
    const char * ptr = static_cast<const char*>(buffer);
    ptr += (m_Dimensions[1]-(h+1))*m_Dimensions[0]*bpp;
    if (bpp == 1)
      {
      for (i = 0; i < m_Dimensions[0]; i++)
        {
        m_Ofstream.write(ptr,sizeof(char));
        ptr++;
        }
      for (i = 0; i < paddedBytes; i++)
        {
        m_Ofstream.write(&paddingValue,sizeof(char));
        }
      }
    if (bpp == 3)
      {
      for (i = 0; i < m_Dimensions[0]; i++)
        {
        ptr += 2;
        m_Ofstream.write(ptr,sizeof(char));
        ptr--;
        m_Ofstream.write(ptr,sizeof(char));
        ptr--;
        m_Ofstream.write(ptr,sizeof(char));
        ptr += 3;
        }
      for (i = 0; i < paddedBytes; i++)
        {
        m_Ofstream.write(&paddingValue,sizeof(char));
        }
      }
    if (bpp == 4)
      {
      for (i = 0; i < m_Dimensions[0]; i++)
        {
        ptr += 3;
        m_Ofstream.write(ptr,sizeof(char));
        ptr--;
        m_Ofstream.write(ptr,sizeof(char));
        ptr--;
        m_Ofstream.write(ptr,sizeof(char));
        ptr--;
        m_Ofstream.write(ptr,sizeof(char));
        ptr += 4;
        }
      for (i = 0; i < paddedBytes; i++)
        {
        m_Ofstream.write(&paddingValue,sizeof(char));
        }
      }
    }
}

/** Print Self Method */
void BMPImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "Depth " << m_Depth << "\n";
  os << indent << "FileLowerLeft " << m_FileLowerLeft << "\n";
  os << indent << "BitMapOffset " << m_BitMapOffset << "\n";
  if(m_Allow8BitBMP)
    {
    os << indent << "m_Allow8BitBMP : True" << "\n";
    }
  else
    {
    os << indent << "m_Allow8BitBMP : False" << "\n";
    }
  os << indent << "BMPCompression = " << m_BMPCompression << "\n";
  os << indent << "DataSize = " << m_BMPDataSize << "\n";
}

} // end namespace itk