2011-11-18 95 views
2

我有這樣的代碼,我發現在這裏,它找到一個像素的顏色的圖像:「<Error>:CGContextDrawImage:無效的情況下爲0x0」

+ (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。它不會崩潰應用程序,但顯然我不希望在那裏發生錯誤。

對此有何建議?

回答

10

這通常是由於CGBitmapContextCreate因標誌,bitsPerComponent等不受支持的組合而失敗。嘗試刪除kCGBitmapByteOrder32Big標誌;有一個Apple doc that lists all the possible context formats - 尋找「支持的像素格式」。

+2

kCGBitmapByteOrder32Big?你在哪裏看到?我沒跟着你。 – RyeMAC3

+1

等一下,找出它....看下面。 – RyeMAC3

+0

對我來說,在某些情況下,不支持的組合將零寬度和/或高度傳遞給CGBitmapContextCreate。必須添加一個檢查來跳過這些。 –

3

呃,我想通了。真傻。

當我第一次進入視圖時,UIImageView是空白的,所以該方法是針對空的UIIMageView調用的。有道理,它會與「無效的上下文」崩潰。當然! UIIMageView是空的。它如何獲得不在那裏的圖像的寬度和高度?

如果我註釋掉方法,選擇一個圖像,然後將該方法放回原處。說得通。

我只是把一個if/else語句只在圖像視圖不是空的時候調用該方法。

相關問題