2

我有一组代码获取存储在 UIImageView 中的图像并修改其内容以复制到不同 UIImageView 的新图像中。问题是当我分析项目时,这段代码总是从我的编译器收到内存警告。我尝试以多种方式实现此代码,但我总是收到不同类型的内存警告。编译器的输出显示“调用函数 'CGBitMapContextCreateImage' 返回一个具有 +1 保留计数的核心基础对象”,这导致图像对象的保留计数为 +1。如果我自动释放图像对象,编译器会发出内存警告,自动释放被调用多次,并且图像对象最初的保留计数为 0。

这两个编译器警告不是矛盾的吗?如何修复此代码以确保不会发生内存泄漏?

-(UIImage *) makeImageLight{

UIImage * image = self.masterImage.image;

NSUInteger width = image.size.width;
NSUInteger height = image.size.height;
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = width * bytesPerPixel;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);

CGColorSpaceRelease(colorSpace);

CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height}, image.CGImage);

UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);


for (size_t i = 0; i < CGBitmapContextGetWidth(bmContext); i++)
{
    for (size_t j = 0; j < CGBitmapContextGetHeight(bmContext); j++)
    {
        int pixel = j * CGBitmapContextGetWidth(bmContext) + i;

        pixel = pixel * 4;

        UInt8 red = data[pixel + 1];         // If you need this info, enable it
        UInt8 green = data[pixel + 2]; // If you need this info, enable it
        UInt8 blue = data[pixel + 3];    // If you need this info, enable it

        red = ((255 - red) * .3) + red;
        green = ((255 - green) * .3) + green;

        data[pixel + 1] = red;
        data[pixel + 2] = green;
        data[pixel + 3] = blue;

    }
}

// memory warning occurs in the following line:

image = [UIImage imageWithCGImage:CGBitmapContextCreateImage(bmContext)];

CGContextRelease(bmContext);

return image;

}

没关系,我通过添加以下代码来修复它以释放从上下文创建的 CGImage:

CGImageRef imageRef = CGBitmapContextCreateImage(bmContext);

image = [UIImage imageWithCGImage:imageRef];

CGImageRelease(imageRef);
4

1 回答 1

4

您使用 CGBitmapContextCreateImage() 创建一个 CGImage,但您还没有发布该 CGImage

您需要UIImage按如下方式拆分创建行:

CGImageRef cgimage = CGBitmapContextCreateImage(bmContext);
image = [UIImage imageWithCGImage:cgimage];
CGImageRelease(cgimage);
于 2012-11-05T08:50:21.780 回答