2009-08-11 89 views
2

例如,我有一個UIImage(如果需要,我可以從中獲取CGImage,CGLayer等),並且我想用藍色(0,0)替換所有紅色像素(1,0,0) ,1)。我有代碼找出哪些像素是目標顏色(見this SO question & answer),我可以在rawData中替換適當的值,但(a)我不知道如何從我的rawData緩衝區取回UIImage,並且(a)我不知道如何從我的rawData緩衝區取回UIImage, (b)似乎我可能會錯過一個內置的內置模塊,它會自動爲我完成所有這些工作,節省了我的悲痛。在UIImage(或其衍生產品)中,如何將一種顏色替換爲另一種顏色?

謝謝!

回答

9

好的,所以我們把UIImage放入了一個rawBits緩衝區(參見原始問題中的鏈接),然後我們將緩衝區中的數據轉換爲我們喜歡的(即將所有紅色組件(每四個字節)設置爲0 ,作爲一個測試),現在需要獲得一個新的UIImage來表示這些旋轉的數據。

我在Erica Sudan's iPhone Cookbook,第7章(圖片),例12(位圖)找到答案。有關電話是CGBitmapContextCreate(),以及相關的代碼是:

+ (UIImage *) imageWithBits: (unsigned char *) bits withSize: (CGSize) 
size 
{ 
    // Create a color space 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    if (colorSpace == NULL) 
    { 
     fprintf(stderr, "Error allocating color space\n"); 
     free(bits); 
     return nil; 
    } 

    CGContextRef context = CGBitmapContextCreate (bits, size.width, 
size.height, 8, size.width * 4, colorSpace, 
kCGImageAlphaPremultipliedFirst); 
    if (context == NULL) 
    { 
     fprintf (stderr, "Error: Context not created!"); 
     free (bits); 
     CGColorSpaceRelease(colorSpace); 
     return nil; 
    } 

    CGColorSpaceRelease(colorSpace); 
    CGImageRef ref = CGBitmapContextCreateImage(context); 
    free(CGBitmapContextGetData(context)); 
    CGContextRelease(context); 

    UIImage *img = [UIImage imageWithCGImage:ref]; 
    CFRelease(ref); 
    return img; 
} 

希望這是有用的網站未來spelunkers!

+1

羞愧沒有多少人使用這種功能,你應該得到更多的功勞。 – 2010-10-22 09:22:30

相關問題