2011-07-12 47 views
2

我有一個ByteArray字節數組的UIImage Objective-C的

unsigned char *outputData = (unsigned char *)malloc(sizeof(unsigned char) * w * h * 4); 

    outputData[y * h * 4 + x * 4 + 0] = all; //alpha value 
    outputData[y * h * 4 + x * 4 + 1] = red; //red value 
    outputData[y * h * 4 + x * 4 + 2] = gre; //green value 
    outputData[y * h * 4 + x * 4 + 3] = blu; //blue value 

      //h... total image height 
      //y,x ... current y and x value from the matrix 

現在我想這個數據轉換成UIImage的。這是如何運作的?我試過了:

NSData *outdata = [NSData dataWithBytes:outputData length:sizeof(unsigned char) * w * h * 4]; 
UIImage *newimage = [UIImage imageWithData:outdata]; 

但是,這似乎不是正確的解決方案。請幫忙。

+0

好的我認爲我解決了它..我發現imageWithData只是創建具有格式(PNG,JPEG)圖像..所以我需要創建一個上下文第一權利? – Marco

回答

10
CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB(); 
    CGContextRef bitmapContext=CGBitmapContextCreate(outputData, w, h, 8, 4*w, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault); 
    CFRelease(colorSpace); 
    free(outputData); 
    CGImageRef cgImage=CGBitmapContextCreateImage(bitmapContext); 
    CGContextRelease(bitmapContext); 

    UIImage * newimage = [UIImage imageWithCGImage:cgImage]; 
    CGImageRelease(cgImage); 
+1

非常感謝。工作完美。 (只需將kCGImageAlphaPrepultipliedLast更改爲kCGImageAlphaPrepultipliedFirst) – Marco

+0

請將此答案標記爲正確的答案,因爲它工作正常;) –