+wxImage wxDIB::ConvertToImage() const
+{
+ wxCHECK_MSG( IsOk(), wxNullImage,
+ wxT("can't convert invalid DIB to wxImage") );
+
+ // create the wxImage object
+ const int w = GetWidth();
+ const int h = GetHeight();
+ wxImage image(w, h, false /* don't bother clearing memory */);
+ if ( !image.Ok() )
+ {
+ wxFAIL_MSG( wxT("could not allocate data for image") );
+ return wxNullImage;
+ }
+
+ const int bpp = GetDepth();
+ if ( bpp == 32 )
+ {
+ image.SetAlpha();
+ }
+
+ // this is the same loop as in Create() just above but with copy direction
+ // reversed
+ const int dstBytesPerLine = w * 3;
+ const int srcBytesPerLine = GetLineSize(w, bpp);
+ unsigned char *dst = image.GetData() + ((h - 1) * dstBytesPerLine);
+ unsigned char *alpha = image.HasAlpha() ? image.GetAlpha() + (h - 1)*w
+ : NULL;
+ const unsigned char *srcLineStart = (unsigned char *)GetData();
+ for ( int y = 0; y < h; y++ )
+ {
+ // copy one DIB line
+ const unsigned char *src = srcLineStart;
+ for ( int x = 0; x < w; x++ )
+ {
+ dst[2] = *src++;
+ dst[1] = *src++;
+ dst[0] = *src++;
+
+ dst += 3;
+
+ if ( alpha )
+ *alpha++ = *src++;
+ }
+
+ // pass to the previous line in the image
+ dst -= 2*dstBytesPerLine;
+ if ( alpha )
+ alpha -= 2*w;
+
+ // and to the next one in the DIB
+ srcLineStart += srcBytesPerLine;
+ }
+
+ return image;
+}
+