ByteArrayExt fix
Added missing CRC field on IEND chunk.
/**
* Copyright yonatan ( http://wonderfl.net/user/yonatan )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/mEon
*/
// forked from keim_at_Si's convert ByteArray to PNG image
package {
import flash.events.*;
import flash.display.*;
import com.bit101.components.*;
public class main extends Sprite {
public function main() {
var me:Sprite = this, imageWidth:Number = 0;
new Label(me, 140, 4, "Image width (0 to autosize) :");
new InputText(me, 270, 4, "0", function(e:Event) : void{
imageWidth = Number(e.target.text);
});
new PushButton(me, 4, 4, "load" , function(e:Event) : void {
new ByteArrayExtPatch().browse(function(bae:ByteArrayExtPatch) : void {
me.addChild(new Bitmap(bae.toBitmapData(imageWidth))).y = 30;
new PushButton(me, 4, 40, "save", function(e:Event) : void {
bae.toPNGData(imageWidth).save("ByteArray.png");
});
});
});
}
}
}
import flash.utils.ByteArray;
import org.si.utils.ByteArrayExt;
class ByteArrayExtPatch extends ByteArrayExt {
/** translate to 24bit png data
* @param width png file width, set 0 to calculate automatically.
* @param height png file height, set 0 to calculate automatically.
* @return ByteArrayExt of PNG data
*/
override public function toPNGData(width:int=0, height:int=0) : ByteArrayExt
{
var i:int, imax:int, reqh:int, pixels:int = (this.length+2)/3, y:int,
png:ByteArrayExt = new ByteArrayExt(),
header:ByteArray = new ByteArray(),
content:ByteArray = new ByteArray();
//----- settings
if (width == 0) width = ((int(Math.sqrt(pixels)+65535/65536))+15)&(~15);
reqh = ((int(pixels/width+65535/65536))+15)&(~15);
if (height == 0 || reqh > height) height = reqh;
header.writeInt(width); // width
header.writeInt(height); // height
header.writeUnsignedInt(0x08020000); // 24bit RGB
header.writeByte(0);
imax = pixels - width;
for (y=0, i=0; i<imax; i+=width, y++) {
content.writeByte(0);
content.writeBytes(this, i*3, width*3);
}
content.writeByte(0);
content.writeBytes(this, i*3, this.length-i*3);
imax = (i + width) * 3;
for (i=this.length; i<imax; i++) content.writeByte(0);
imax = width * 3 + 1;
for (y++; y<height; y++) for (i=0; i<imax; i++) content.writeByte(0);
i = this.length;
content.position -= 3;
content.writeByte(i>>>16);
content.writeByte(i>>>8);
content.writeByte(i);
content.compress();
//----- write png data
// signature
png.writeUnsignedInt(0x89504e47);
png.writeUnsignedInt(0x0D0A1A0A);
// IHDR
png_writeChunk(0x49484452, header);
// IDAT
png_writeChunk(0x49444154, content);
// IEND
png_writeChunk(0x49454E44, new ByteArray);
png.position = 0;
return png;
//----- write png chunk
function png_writeChunk(type:uint, data:ByteArray) : void {
png.writeUnsignedInt(data.length);
var crcStartAt:uint = png.position;
png.writeUnsignedInt(type);
png.writeBytes(data);
png.writeUnsignedInt(calculateCRC32(png, crcStartAt, png.position - crcStartAt));
}
}
}