Alter PNG bit depth in backend-agg

I'm using the AGG backend to output graphs as PNG files, but I have had users complain that the resulting files are too large (the images are being served via a web server).

The graphs are simple line graphs with less than 8 colours, so I'm trying to change src/_backend_agg.cpp to output a 4 bit per pixel PNG using PNG_COLOR_TYPE_PALETTE, rather than the default PNG_COLOR_TYPE_RGB_ALPHA. The code currently looks like this (the changes I have made have "PHB" in the comments):

src/_backend_agg.cpp, line 2077:
  // PHB inserted code start
  info_ptr->valid |= PNG_INFO_PLTE;
  info_ptr->palette = (png_color*)malloc(256 * sizeof (png_color));
  info_ptr->num_palette = 256;
  // PHB inserted code end

  if (setjmp(png_ptr->jmpbuf)) {
    if (fpclose) fclose(fp);
    png_destroy_write_struct(&png_ptr, &info_ptr);
    delete [] row_pointers;
    throw Py::RuntimeError("Error building image");
  }

  png_init_io(png_ptr, fp);
  png_set_IHDR(png_ptr, info_ptr,
               width, height, 4, // PHB Changed from 8 BPP
               PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE, // PHB changed from PNG_COLOR_TYPE_RGB_ALPHA
               PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

  // this a a color image!
  sig_bit.gray = 0;
  sig_bit.red = 4; // PHB Changed from 8 to 4
  sig_bit.green = 4; // PHB Changed from 8 to 4
  sig_bit.blue = 4; // PHB Changed from 8 to 4
  /* if the image has an alpha channel then */
  sig_bit.alpha = 0; // PHB Changed from 8 to 0

This doesn't crash, but it outputs a stretched image - it looks like the pixels that make up the image have zero pixels in between. I've had a look through the libpng documentation here: http://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-4.1 but there isn't a lot of detail about how to set up palettes, etc. Does anyone have any advice for me on how to get this working?

Cheers

Peter