2012-10-13 60 views
2

我目前在C數組中有一些圖像數據,其中包含RGBA數據。將C數組轉換爲UIImage(iOS版)

float array[length][4] 

我想要得到它到一個UIImage,它看起來像這些初始化與文件,NSData和URLs。由於其他兩種方法很慢,我最感興趣的是NSData方法。

我可以得到所有這些價值觀轉化爲一個N​​SArray像這樣:

for (i=0; i<image.size.width * image.size.height; i++){ 
    replace = [UIColor colorWithRed:array[i][0] green:array[i][1] blue:array[i][2] alpha:array[i][3]]; 
    [output replaceObjectAtIndex:i withObject:replace]; 
} 

所以,我有一個NSArray中充滿了是的UIColor對象。我嘗試了很多方法,但是如何將其轉換爲UIImage?

我認爲這將是直截了當的。功能sorta像imageWithData:data R:0 B:1 G:2 A:3 length:length width:width length:length會很好,但沒有功能,據我所知。

回答

5

imageWithData:是指標準圖像文件格式的圖像數據,例如,您在內存中使用的PNG或JPEG文件。它不適合從原始數據創建圖像。爲此,您通常會創建一個位圖圖形上下文,將數組,像素格式,大小等傳遞給CGBitmapContextCreate函數。在創建位圖上下文時,可以使用CGBitmapContextCreateImage從中創建一個圖像,該圖像爲您提供了一個CGImageRef,您可以將其傳遞給UIImage方法imageWithCGImage:

下面是一個基本的例子,它創建一個具有一個紅色像素和一個綠色像素的微小1×2像素圖像。它只是使用那些意在顯示色彩組件的順序硬編碼的像素值,通常情況下,你會從別的地方當然得到這樣的數據:

size_t width = 2; 
size_t height = 1; 
size_t bytesPerPixel = 4; 
//4 bytes per pixel (R, G, B, A) = 8 bytes for a 1x2 pixel image: 
unsigned char rawData[8] = {255, 0, 0, 255, //red 
          0, 255, 0, 255}; //green 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
size_t bytesPerRow = bytesPerPixel * width; 
size_t bitsPerComponent = 8; 
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); 

CGImageRef cgImage = CGBitmapContextCreateImage(context); 
//This is your image: 
UIImage *image = [UIImage imageWithCGImage:cgImage]; 
//Don't forget to clean up: 
CGImageRelease(cgImage); 
CGColorSpaceRelease(colorSpace); 
CGContextRelease(context); 
+0

你能不能給我一些更多的細節?如果你願意的話,一個例子會非常有幫助。據我所知,我用'CGBitmapContextCreate'函數創建了'CGBitmapContextRef',但是在任何地方都找不到'CGBitmapContextRef'。然後我將該創建傳遞給'CGBitmapContextCreateImage',然後將其傳遞給'imageWithCGImage.'正確? – Scott

+0

對不起,'CGBitmapContextRef'不正確,'CGBitmapContextCreate'函數實際上只是返回一個常規的'CGContextRef'。我會看看我能否找到一個簡單的例子... – omz

+0

我已經給答案添加了一個基本示例。 – omz