Anderson Green
Anderson Green

Reputation: 31840

Save an array of pixels to a file

In the Haxe programming language, is there any cross-language way to save an array of pixel data to a file (e. g., in BMP or PNG format)?

class SavePixelsToFile {
  static function main(){
    //how can I save this array of pixel data to a file? It is a simple 2D array of RGB arrays, with the red, green, and blue components in the respective order.
    var arr = [
      [[0, 0, 0],[255, 255, 255]],
      [[255, 255, 255],[0, 0, 0]]
      ];
  }
}

Upvotes: 0

Views: 845

Answers (2)

Matthew Spencer
Matthew Spencer

Reputation: 116

The format library will do what you want. http://code.google.com/p/hxformat/

Install this library: haxelib install format

Link it in your hxml file using: -lib format

To write image data to a file, do the following:

function writePixels24(file:String, pixels:haxe.io.Bytes, width:Int, height:Int) {
    var handle = sys.io.File.write(file, true);
    new format.png.Writer(handle)
        .write(format.png.Tools.build24(width, height, pixels));
    handle.close();
}

var bo = new haxe.io.BytesOutput();
for (pixel in pixels)
    for (channel in pixel) 
         bo.writeByte(channel);
var bytes = bo.getBytes();
writePixels24("Somefile.png", bytes);

This will work for targets that have the sys.* package (Not flash). you can still generate the png without the sys.* package, but will need an alternate method of saving the file.

Upvotes: 2

kmkaplan
kmkaplan

Reputation: 18960

An easy to write format is PPM. The netpbm tools can easily manipulate those and also convert to many formats including PBM and PNG.

Upvotes: 0

Related Questions