title: How do I modify the palette of an indexed PNG at runtime on iOS?
body: <p>I have a series of PNG images that use indices into a palette for color (PNG color type 3). In some cases, I need to make a copy of an image where some of the entries in the palette are modified. In this way we recolor a source PNG over and over.</p>
  
  <p>In Java, this is handled by getting the RGB values from an <code>IndexedColorModel</code>, modifying the values and creating a new <code>IndexedColorModel</code>, and creating a new <code>BufferedImage</code> with the source image's raster data and the new color model.</p>
  
  <p>In Actionscript, I had to read in the PNG bytes as a bare <code>ByteArray</code>, find the palette chunk, modify the values, then have the runtime load up the image from the <code>ByteArray</code>. </p>
  
  <p>I'm now looking to implement the same system for iOS via MonoTouch (which I'm new to), but I've hit a wall. I believe the Actionscript approach would work here as well, but it would be nice to avoid working at such a low level this time, and it looks like I can get close.</p>
  
  <p>If I'm starting from a <code>UIImage</code>, I can get the color space with <code>UIImage.CGImage.ColorSpace</code>. I can verify that it's an indexed color model with <code>colorSpace.Model</code>. What I'm not sure about is how I get the actual array of palette bytes.</p>
  
  <p>And then on the other side, how do I create a new image with the new palette? <code>CGImage.WithColorSpace</code> looks like it would do what I want... maybe? And then I have to be able to create a color space with my new palette: On the surface, <code>CGColorSpace.CreateIndexed</code> looks like what I want, but I'm unclear on how the <code>baseSpace</code> parameter is used. I want to create a <code>CGColorSpace</code> with a totally new color palette that I provide, and then use the original image's indices with the new palette. Maybe I'm misunderstanding exactly what <code>CGColorSpace</code> is used for.</p>