iOS校验图片每个像素透明度
2022-03-04 本文已影响0人
ONE2
- (void)canAsNightClubBodyImage:(void(^)(BOOL can))finish {
CGImageRef imgref = self.CGImage;
// 获取图片宽高(总像素数)
size_t width = CGImageGetWidth(imgref);
size_t height = CGImageGetHeight(imgref);
// 每行像素的总字节数
size_t bytesPerRow = CGImageGetBytesPerRow(imgref);
// 每个像素多少位(RGBA每个8位,所以这里是32位) ps:(一个字节8位)
size_t bitsPerPixel = CGImageGetBitsPerPixel(imgref);
CGDataProviderRef dataProvider = CGImageGetDataProvider(imgref);
CFDataRef data = CGDataProviderCopyData(dataProvider);
UInt8 *buffer = (UInt8*)CFDataGetBytePtr(data);// 图片数据的首地址
int area = 24;
int total = 0;
int alphaZero = 0;
// left top
for (int x = 0; x < area; x ++ ) {
for (int y = 0; y < area; y ++) {
total ++;
//每个像素的首地址
UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
// UInt8 red = *pt;
// UInt8 green = *(pt+1); //指针向后移动一个字节
// UInt8 blue = *(pt+2);
UInt8 alpha = *(pt+3);
if (alpha < 0.1) {
alphaZero ++;
}
}
}
// left bottom
for (int x = 0; x < area; x ++ ) {
for (long y = height - area; y < height; y ++) {
total ++;
UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
UInt8 alpha = *(pt+3);
if (alpha < 0.1) {
alphaZero ++;
}
}
}
// right top
for (long x = width - area; x < width; x ++ ) {
for (int y = 0; y < area; y ++) {
total ++;
UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
UInt8 alpha = *(pt+3);
if (alpha < 0.1) {
alphaZero ++;
}
}
}
// right bottom
for (long x = width - area; x < width; x ++ ) {
for (long y = height - area; y < height; y ++) {
total ++;
UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
UInt8 alpha = *(pt+3);
if (alpha < 0.1) {
alphaZero ++;
}
}
}
// 有这行会崩溃 CGDataProviderRelease(dataProvider);
float percent = alphaZero*1.0/total;
finish(percent > 0.2);
}