无法更改UIImage中像素的颜色

时间:2016-03-08 03:34:05

标签: ios objective-c uiimage core-graphics

我已经通过使用不同的代码解决了我的问题。我只想知道下一个有什么问题?

我想使用位图数据更改UIImage中每个像素的颜色。我的代码如下:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UIImage *image = self.imageViewMain.image;

    CGImageRef imageRef = image.CGImage;
    NSData *data        = (NSData *)CFBridgingRelease(CGDataProviderCopyData(CGImageGetDataProvider(imageRef)));
    char *pixels        = (char *)[data bytes];

    // this is where we manipulate the individual pixels
    for(int i = 1; i < [data length]; i += 3)
    {
        int r = i;
        int g = i+1;
        int b = i+2;
        int a = i+3;

        pixels[r]   = 0; // eg. remove red
        pixels[g]   = pixels[g];
        pixels[b]   = pixels[b];
        pixels[a]   = pixels[a];
    }

    // create a new image from the modified pixel data
    size_t width                    = CGImageGetWidth(imageRef);
    size_t height                   = CGImageGetHeight(imageRef);
    size_t bitsPerComponent         = CGImageGetBitsPerComponent(imageRef);
    size_t bitsPerPixel             = CGImageGetBitsPerPixel(imageRef);
    size_t bytesPerRow              = CGImageGetBytesPerRow(imageRef);

    CGColorSpaceRef colorspace      = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo         = CGImageGetBitmapInfo(imageRef);
    CGDataProviderRef provider      = CGDataProviderCreateWithData(NULL, pixels, [data length], NULL);

    CGImageRef newImageRef = CGImageCreate (
                                            width,
                                            height,
                                            bitsPerComponent,
                                            bitsPerPixel,
                                            bytesPerRow,
                                            colorspace,
                                            bitmapInfo,
                                            provider,
                                            NULL,
                                            false,
                                            kCGRenderingIntentDefault
                                            );
    // the modified image
    UIImage *newImage   = [UIImage imageWithCGImage:newImageRef];

    // cleanup
    free(pixels);
    CGImageRelease(imageRef);
    CGColorSpaceRelease(colorspace);
    CGDataProviderRelease(provider);
    CGImageRelease(newImageRef);
}

但是当此代码运行时 - 我会看到EXC_BAD_ACCESS 错误,如下图所示:

enter image description here

以下是调试的更多信息:

enter image description here

我错过了什么或做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试为像素数组分配内存,如下面的代码

char *pixels = (char *)malloc(data.length);
memcpy(pixels, [data bytes], data.length);

如果不需要像素,请通过调用free(pixels)

释放此内存