title: FreeImage: Pixel data accessed by FreeImage_GetBits is not correct (data + size)
body: <p>I'm using the <a href="http://freeimage.sourceforge.net/" rel="nofollow">FreeImage 3.15.4 library</a> to analyze PNG images. I'm basically trying to build a simple data structure of consisting of a palette of all colors as well as an array version of the image per-pixel data consisting of indexes into the palette.</p>
  
  <p>The thing is that <code>FreeImage_GetBits</code> seems to be returning a pointer to invalid data and I'm not sure why. I am able to read the width and height of the PNG file correctly, but the data pointed to by <code>FreeImage_GetBits</code> is just garbage data, and appears to be of an odd size. No matter how many times I run the program, it consistently dies in the same place, when <code>iPix</code> in the code below is equal to 131740. I get a C0000005 error accessing bits[131740] in the std::find call. The actual and reported PNG image size is 524288.</p>
  
  <p>Furthermore, I've tried this code with smaller images that I myself have built and they work fine. The PNG I'm using is provided my a third party, and does not appear to be corrupt in anyway (Photoshop opens it, and DirectX can process and use it normally)</p>
  
  <p>Any ideas?</p>
  
  <p>Here's the data declarations:</p>
  
  <pre><code>struct Color
  {
      char b; // Blue
      char g; // Green
      char r; // Red
      char a; // Alpha value
  
      bool operator==( const Color&amp; comp )
      {
          if ( a == comp.a &amp;&amp;
               r == comp.r &amp;&amp;
               g == comp.g &amp;&amp;
               b == comp.b )
              return TRUE;
          else
              return FALSE;
      }
  };
  
  typedef std::vector&lt;Color&gt; ColorPalette; // Array of colors forming a palette
  </code></pre>
  
  <p>And here's the code that does the color indexing:</p>
  
  <pre><code>// Read image data with FreeImage
  unsigned int imageSize = FreeImage_GetWidth( hImage ) * FreeImage_GetHeight( hImage );
  
  unsigned char* pData = new unsigned char[imageSize];
  
  // Access bits via FreeImage
  FREE_IMAGE_FORMAT fif;
  FIBITMAP* hImage;
  fif = FreeImage_GetFIFFromFilename( fileEntry.name.c_str() );
  if( fif == FIF_UNKNOWN )
  {
      return false;
  }
  hImage = FreeImage_Load( fif, filename );
  BYTE* pPixelData = NULL;
  pPixelData = FreeImage_GetBits( hImage );
  if ( pPixelData == NULL )
  {
      return false;
  }
  
  Color* bits = (Color*)pPixelData;
  ColorPalette palette;
  
  for ( unsigned int iPix = 0; iPix &lt; imageSize; ++iPix )
  {
      ColorPalette::iterator it;
  
      if( ( it = std::find( palette.begin(), palette.end(), bits[iPix] ) ) == palette.end() )
      {
          pData[iPix] = palette.size();
          palette.push_back( bits[iPix] );
      }
      else
      {
          unsigned int index = it - palette.begin();
          pData[iPix] = index;
      }
  }
  </code></pre>