检测图像中的透明度

问题描述 投票:8回答:1

我需要确定png图像是否包含任何透明度 - 实现此目的的最有效代码是什么?

ios core-graphics
1个回答
18
投票

将png转换为pixelbuffer并使用vimage计算颜色分布的直方图。然后检查alpha通道直方图。 vimage比逐个浏览像素要快得多。

CVPixelBufferRef pxbuffer = NULL;

vImagePixelCount histogramA[256];
vImagePixelCount histogramR[256];
vImagePixelCount histogramG[256];
vImagePixelCount histogramB[256];
vImagePixelCount *histogram[4];
histogram[0] = histogramA;
histogram[1] = histogramR;
histogram[2] = histogramG;
histogram[3] = histogramB;
vImage_Buffer vbuff;
vbuff.height = CVPixelBufferGetHeight(pxbuffer);
vbuff.width = CVPixelBufferGetWidth(pxbuffer);
vbuff.rowBytes = CVPixelBufferGetBytesPerRow(pxbuffer);

vbuff.data = pxbuffer; 
vImage_Error err = vImageHistogramCalculation_ARGB8888 (&vbuff,histogram, 0);
if (err != kvImageNoError) NSLog(@"%ld", err);

int trans = 255 //How little transparency you want to include
BOOL transparent = NO;      
for(int i=0; i<trans; i++){
   if(histogram[0][i]>0) transparent = YES;
}

vimage假设颜色在缓冲区中按顺序排列ARGB。如果你有其他的东西,例如BGRA,你只需检查直方图[3] [i]。

更快的可能是首先使用vImageConvert_ARGB8888toPlanar8将缓冲区拆分为四个平面缓冲区,然后使用vImageHistogramCalculation_Planar8在alfa缓冲区上进行直方图计算。

您可以将png作为CGImage打开,并使用vImageBuffer_initWithCGImage将其直接转换为vimage缓冲区(请参阅WWDC 2014上的会话703)。

最后,另一种方法是使用Core Image来计算直方图。

© www.soinside.com 2019 - 2024. All rights reserved.