+ wxPalette *palette = NULL; // entries for quantized images
+ wxUint8 *rgbquad = NULL; // for the RGBQUAD bytes for the colormap
+ wxImage *q_image = NULL; // destination for quantized image
+
+ // if <24bpp use quantization to reduce colors for *some* of the formats
+ if ( (format == wxBMP_1BPP) || (format == wxBMP_4BPP) ||
+ (format == wxBMP_8BPP) || (format == wxBMP_8BPP_PALETTE))
+ {
+ // make a new palette and quantize the image
+ if (format != wxBMP_8BPP_PALETTE)
+ {
+ q_image = new wxImage();
+
+ // I get a delete error using Quantize when desired colors > 236
+ int quantize = ((palette_size > 236) ? 236 : palette_size);
+ // fill the destination too, it gives much nicer 4bpp images
+ wxQuantize::Quantize( *image, *q_image, &palette, quantize, 0,
+ wxQUANTIZE_FILL_DESTINATION_IMAGE );
+ }
+ else
+ {
+#if wxUSE_PALETTE
+ palette = new wxPalette(image->GetPalette());
+#endif // wxUSE_PALETTE
+ }
+
+ int i;
+ unsigned char r, g, b;
+ rgbquad = new wxUint8 [palette_size*4];
+
+ for (i=0; i<palette_size; i++)
+ {
+#if wxUSE_PALETTE
+ if (!palette->GetRGB( i, &r, &g, &b ))
+#endif // wxUSE_PALETTE
+ r = g = b = 0;
+
+ rgbquad[i*4] = b;
+ rgbquad[i*4+1] = g;
+ rgbquad[i*4+2] = r;
+ rgbquad[i*4+3] = 0;
+ }
+ }
+ // make a 256 entry greyscale colormap or 2 entry black & white
+ else if ((format == wxBMP_8BPP_GREY) || (format == wxBMP_8BPP_RED) ||
+ (format == wxBMP_1BPP_BW))
+ {
+ int i;
+ rgbquad = new wxUint8 [palette_size*4];
+
+ for (i=0; i<palette_size; i++)
+ {
+ // if 1BPP_BW then just 0 and 255 then exit
+ if (( i > 0) && (format == wxBMP_1BPP_BW)) i = 255;
+ rgbquad[i*4] = i;
+ rgbquad[i*4+1] = i;
+ rgbquad[i*4+2] = i;
+ rgbquad[i*4+3] = 0;
+ }
+ }
+
+ // if the colormap was made, then it needs to be written
+ if (rgbquad)
+ {
+ if (!stream.Write(rgbquad, palette_size*4))
+ {
+ if (verbose)
+ wxLogError(_("BMP: Couldn't write RGB color map."));
+ delete [] rgbquad;
+#if wxUSE_PALETTE
+ delete palette;
+#endif // wxUSE_PALETTE
+ delete q_image;
+ return FALSE;
+ }
+ delete []rgbquad;
+ }
+
+ // pointer to the image data, use quantized if available