使用AS3检查PNG图像是否包含(半)透明像素

Hoa*_*ynh 2 png pixel image-processing transparent actionscript-3

我想使用AS3检查(32位ARGB)PNG图像,看它是否包含任何(半)透明像素(返回truefalse).最快的方法是什么?

inh*_*han 5

很久以前我一直在寻找相同的东西,我尝试使用循环来检查每个像素.但这需要花费大量时间并消耗了大量的CPU.幸运的是,我们有BitmapData.compare()方法,如果在比较的BitmapData对象中存在任何差异,则输出Bitmapdata.

还有BitmapData.transparent属性,它实际上直接给你答案作为布尔值.但我自己从未在加载的图像上直接使用它.

import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Point;

var ldr:Loader = new Loader();
var req:URLRequest = new URLRequest('someImage.png');
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE,imgLoaded);
ldr.load(req);

function imgLoaded(e:Event):void {
    var l:Loader = e.target.loader,
    bmp:Bitmap = l.content as Bitmap,
    file:String = l.contentLoaderInfo.url.match(/[^\/\\]+$/)[0];
    trace(bmp.bitmapData.transparent);
    // I think this default property should do it but
    // in case it does not, here's another approach:
    var trans:Boolean = isTransparent(bmp.bitmapData);
    trace(file,'is'+(trans ? '' : ' not'),'transparent');
}

function isTransparent(bmpD:BitmapData):Boolean {
    var dummy:BitmapData = new BitmapData(bmpD.width,bmpD.height,false,0xFF6600);
    // create a BitmapData with the size of the source BitmapData
    // painted in a color (I picked orange)
    dummy.copyPixels(bmpD,dummy.rect,new Point());
    // copy pixels of the original image onto this orange BitmapData
    var diffBmpD:BitmapData = bmpD.compare(dummy) as BitmapData;
    // this will return null if both BitmapData objects are identical
    // or a BitmapData otherwise
    return diffBmpD != null;
}
Run Code Online (Sandbox Code Playgroud)

  • @ Apocalyptic0n3我用一些大的PNG图像(大小为2-8MB)进行了几次测试,并且@inhan的两种方法都能快速实现.相对而言,像素到像素的方法工作得慢得多,但令人惊讶的是我的期望.仅供参考,在一次测试中,`BitmapData.transparent`在14ms内工作,`BitmapData.compare()`工作在30ms,像素到像素方法工作在590ms.(我的CPU是Intel Core i7-2600K @ 3.4Ghz.) (2认同)