我正在编写此方法来计算图像的平均 R、G、B 值。以下方法将 UIImage 作为输入,并返回一个包含输入图像的 R、G、B 值的数组。不过我有一个问题:如何/在哪里正确发布 CGImageRef?
-(NSArray *)getAverageRGBValuesFromImage:(UIImage *)image
{
CGImageRef rawImageRef = [image CGImage];
//This function returns the raw pixel values
const UInt8 *rawPixelData = CFDataGetBytePtr(CGDataProviderCopyData(CGImageGetDataProvider(rawImageRef)));
NSUInteger imageHeight = CGImageGetHeight(rawImageRef);
NSUInteger imageWidth = CGImageGetWidth(rawImageRef);
//Here I sort the R,G,B, values and get the average over the whole image
int i = 0;
unsigned int red = 0;
unsigned int green = 0;
unsigned int blue = 0;
for (int column = 0; column< imageWidth; column++)
{
int r_temp = 0;
int g_temp = 0;
int b_temp = 0;
for (int row = 0; row < imageHeight; row++) {
i = (row * imageWidth + column)*4;
r_temp += (unsigned int)rawPixelData[i];
g_temp += (unsigned int)rawPixelData[i+1];
b_temp += (unsigned int)rawPixelData[i+2];
}
red += r_temp;
green += g_temp;
blue += b_temp;
}
NSNumber *averageRed = [NSNumber numberWithFloat:(1.0*red)/(imageHeight*imageWidth)];
NSNumber *averageGreen = [NSNumber numberWithFloat:(1.0*green)/(imageHeight*imageWidth)];
NSNumber *averageBlue = [NSNumber numberWithFloat:(1.0*blue)/(imageHeight*imageWidth)];
//Then I store the result in an array
NSArray *result = [NSArray arrayWithObjects:averageRed,averageGreen,averageBlue, nil];
return result;
}
我尝试了两件事: 选项 1:我保持原样,但在几个周期 (5+) 后程序崩溃并且我收到“内存不足警告错误”
选项 2:我在方法返回之前添加一行 CGImageRelease(rawImageRef) 。现在它在第二个周期后崩溃,我收到了我传递给该方法的 UIImage 的 EXC_BAD_ACCESS 错误。当我尝试在 Xcode 中分析(而不是 RUN)时,我在这一行收到以下警告“调用者此时不拥有的对象的引用计数不正确递减”
我应该在哪里以及如何发布 CGImageRef?
谢谢!