Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- By Martin Sebastian Wain, 2014.
- To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
- http://creativecommons.org/publicdomain/zero/1.0/
- */
- static public function encode16ColorXPM2(bd:BitmapData):String {
- var all:Vector.<uint> = bd.getVector(bd.rect);
- var colors:Dictionary = new Dictionary;
- var colIndex:uint = 0;
- var strColors:String = "";
- for(var i:int = all.length-1; i>=0; i--) {
- if(all[i] in colors) continue;
- if(colIndex == 16) { trace("Error: More than 16 colors"); return null; }
- var id:String = String.fromCharCode("a".charCodeAt(0) + colIndex);
- colors[all[i]] = id;
- colIndex++;
- var padded:String = (all[i] & 0xffffff).toString(16);
- while(padded.length<6) padded = "0"+padded;
- strColors += id+" c #"+padded+"\n";
- }
- var ret:String = "! XPM2\n"+bd.width+" "+bd.height+" "+colIndex+" 1\n"+strColors;
- for(var y:int = 0; y<bd.height; y++) {
- for(var x:int = 0; x<bd.width; x++) {
- ret += colors[bd.getPixel32(x, y)];
- }
- ret += "\n";
- }
- return ret;
- }
- static public function decodeXPM2(str:String):BitmapData {
- var lines:Array = str.replace(/\r\n/g,"\n").replace(/\r/g, "\n").split("\n"); //split(/\r|\n|(\r\n)/) aint working
- //Check format
- if(lines[0] != "! XPM2") { trace("Non XPM2 string format"); return null; };
- //Read config
- var config:Array = lines[1].split(" ");
- var w:uint = uint(config[0]);
- var h:uint = uint(config[1]);
- var numColors:uint = uint(config[2]);
- var charPerPx:uint = uint(config[3]);
- var bd:BitmapData = new BitmapData(w,h,false,0);
- var colors:Dictionary = new Dictionary;
- var i:uint = 2;
- //Load colors
- while(numColors--) {
- var colorInfo:Array = lines[i].split(" ");
- if(colorInfo[0].length != charPerPx) { trace(lines[i],"(",i,")","invalid color text-id, should be ",charPerPx,"chars long"); return null; }
- if(colorInfo[1] != "c") { trace(lines[i],"(",i,")","invalid color line format"); return null; }
- if(colorInfo[2].length!=7 || colorInfo[2].substr(0,1) != "#") { trace(lines[i],"(",i,")","invalid rgb format"); return null; }
- colors[colorInfo[0]] = parseInt(colorInfo[2].substr(1), 16) | 0xff000000;
- i++;
- }
- //Load image
- for(var y:int = 0; y<h; y++) {
- for(var x:int=0; x<w; x++) {
- var id:String = lines[i].substr(x*charPerPx, charPerPx);
- if(!(id in colors)) { trace(lines[i],"(",i,":",x*charPerPx,")","invalid color text-id at position"); return null; }
- bd.setPixel32(x, y, colors[id]);
- }
- i++;
- }
- return bd;
- }
Advertisement
Add Comment
Please, Sign In to add comment