Q:

Read a PNG image using Haxe

Using the Haxe programming language, is there any cross-platform way to read a PNG image, and get the pixel data from the image?
I have a file called stuff.png, and I want to obtain an array of RGB values from the image (as an integer array).

A:

Here's an example usage of the Haxe format library to read a PNG file. You need -lib format in your compiler args / build.hxml:
function readPixels(file:String):{data:Bytes, width:Int, height:Int} {
    var handle = sys.io.File.read(file, true);
    var d = new format.png.Reader(handle).read();
    var hdr = format.png.Tools.getHeader(d);
    var ret = {
        data:format.png.Tools.extract32(d),
        width:hdr.width,
        height:hdr.height
    };
    handle.close();
    return ret;
}

Here's an example of how to get ARGB pixel data from the above:
public static function main() {
  if (Sys.args().length == 0) {
    trace('usage: PNGReader <filename>');
    Sys.exit(1);
  }
  var filename = Sys.args()[0];
  var pixels = readPixels(filename);
  for (y in 0...pixels.height) {
    for (x in 0...pixels.width) {
      var p = pixels.data.getInt32(4*(x+y*pixels.width));
      // ARGB, each 0-255
      var a:Int = p>>>24;
      var r:Int = (p>>>16)&0xff;
      var g:Int = (p>>>8)&0xff;
      var b:Int = (p)&0xff;
      // Or, AARRGGBB in hex:
      var hex:String = StringTools.hex(p,8);
      trace('${ x },${ y }: ${ a },${ r },${ g },${ b } - ${ StringTools.hex(p,8) }');
    }
  }

