"错误:CGContextDrawImage:无效的上下文0x0"

3
我有一段代码,是在这里找到的,它可以找到图像中像素的颜色:
+ (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy count:(int)count
{
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

    // First get the image into your data buffer
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = malloc(height * width * 4);
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
    for (int ii = 0 ; ii < count ; ++ii)
    {
        CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
        CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
        CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
        CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
        byteIndex += 4;

        UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
        [result addObject:acolor];
    }

    free(rawData);

    return result;
}

但是在这一行代码 CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); 中,NSLog的输出会提示一个错误<Error>: CGContextDrawImage: invalid context 0x0。虽然它不会崩溃应用程序,但显然我不希望在这里出现错误。

对此有什么建议吗?

2个回答

10

通常是由于CGBitmapContextCreate失败,原因可能是标志、bitsPerComponent等不支持的组合。尝试移除 kCGBitmapByteOrder32Big 标志;有一个Apple文档列出了所有可能的上下文格式 - 查找“支持的像素格式”。


2
kCGBitmapByteOrder32Big?你在哪里看到的?我不明白你的意思。 - RyeMAC3
对我来说,不支持的组合是在某些情况下将零宽度和/或高度传递给CGBitmapContextCreate。必须添加一个检查以跳过这些情况。 - Tomas Andrle

4
当我第一次进入视图时,UIImageView是空的,所以该方法会针对一个空的UIIMageView调用。很明显它会崩溃并显示“无效上下文”。当然!UIIMageView是空的。如果没有图片,它怎么能获取图片的宽度和高度呢?
如果我注释掉这个方法,选择一张图片,然后再把这个方法加回去,就可以正常工作了。这很合理。
我只是添加了一个if/else语句,只有在图像视图不为空时才调用该方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接