Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a PNG image using Haxe

Tags:

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).

like image 359
Anderson Green Avatar asked Oct 22 '22 21:10

Anderson Green


1 Answers

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) }');
    }
  }
like image 122
Matthew Spencer Avatar answered Oct 25 '22 17:10

Matthew Spencer