R – How to get the background color of a loaded swf file

actionscriptactionscript-3flashloader

I'm loading an swf file into my main application using URLLoader, I want to get the background color of the loaded swf file. ( I heard that one solution wold be reading the byte code of the loaded swf )

Best Answer

Yes, You need to look into binary swf data. Here is brief description of swf format. And this is a little detail about different kind of tags. Your requirement is to find out SetBackgroundColor tag(tag type = 9), which commonly is either first or second tag of the swf.
Bytes in swf file follows little endian order, so you need to be careful while reading the data. And mostly they will be compressed(first three bytes will be "CWS") so from 9th bytes onwards (including 9th), all data needs to be decompressed (ByteArray.decompress) before processing.
SomeExample code :)

package {
  import flash.display.*;
  import flash.events.*;
  import flash.net.*;
  import flash.utils.*;
  public class Test1 extends Sprite{
    private var stream:URLStream;
    public function Test1():void {
      stream = new URLStream();
      stream.load(new URLRequest("some.swf"));
      stream.addEventListener(Event.COMPLETE, onComplete);
    }
    private function onComplete(e:Event):void {
      var bytes:ByteArray = new ByteArray();
      bytes.endian = Endian.LITTLE_ENDIAN;
      stream.readBytes(bytes, 0, 8);
      var sig:String = bytes.readUTFBytes(3);
      trace("SIG = " + sig);
      trace("ver = " + bytes.readByte());
      trace("size = " + bytes.readUnsignedInt());
      var compBytes:ByteArray = new ByteArray();
      compBytes.endian = Endian.LITTLE_ENDIAN;
      stream.readBytes(compBytes);
      if (sig == "CWS") {
        compBytes.uncompress();
      }
      var fbyte = compBytes.readUnsignedByte();
      var rect_bitlength = fbyte >> 3;
      var total_bits = rect_bitlength * 4;
      var next_bytes =  Math.ceil((total_bits - 3)/ 8);
      for(var i=0; i<next_bytes; i++) {
        compBytes.readUnsignedByte();
      }
      trace("frameRate = " + compBytes.readUnsignedShort());
      trace("frameCount = " + compBytes.readUnsignedShort());

  while(true) {
    var tagcodelen:Number = compBytes.readUnsignedShort();
    var tagcode:Number = tagcodelen >> 6;
    var taglen:Number = tagcodelen & 0x3F;
    trace("tag code = " + tagcode + "\tlen = " + taglen);
    if (taglen >=63) {
      taglen = compBytes.readUnsignedInt();
    }
    if(tagcode == 9) {
      trace("found background color");
      trace("color is: RED=" + compBytes.readUnsignedByte() +", GREEN = " + compBytes.readUnsignedByte() + ", BLUE = " + compBytes.readUnsignedByte());
      break;
    }
    compBytes.readBytes(new ByteArray(), 0, taglen);
    //break;
  }
}

} }

Related Topic