Skip to content

Instantly share code, notes, and snippets.

@KenneyNL
Created April 1, 2018 01:18
Show Gist options
  • Save KenneyNL/0c8feca306b929dbed93e86339360235 to your computer and use it in GitHub Desktop.
Save KenneyNL/0c8feca306b929dbed93e86339360235 to your computer and use it in GitHub Desktop.
Flash ActionScript 3.0 apply color palette to BitmapData
var colorPalette = [0xFF5a3921, 0xFF6b8c42, 0xFF7bc67b, 0xFFffffb5];
function applyPalette(bitmap:BitmapData, palette:Array){
bitmap.lock();
for(var x = 0; x < bitmap.width; x++){
for(var y = 0; y < bitmap.height; y++){
var pixel = bitmap.getPixel(x, y);
var c:uint = closestColor(pixel, palette);
bitmap.setPixel(x, y, c);
}
}
bitmap.unlock();
}
function colorDistance(color1:uint, color2:uint){
var a = hex2rgb(color1);
var b = hex2rgb(color2);
return (Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b));
}
function closestColor(color:uint, palette:Array){
var distance = 1000;
var pickedColor = 0;
for each(var c in palette){
var d = colorDistance(color, c);
if(d <= distance){ distance = d; pickedColor = c; }
}
return pickedColor;
}
function hex2rgb(color:uint):Object{
var c:Object = {};
c.r = color >> 16 & 0xFF;
c.g = color >> 8 & 0xFF;
c.b = color & 0xFF;
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment