2010-05-13 46 views
1

我想創建與顏色信息的CGImage我已經有轉換位圖圖像信息轉換成CGImage在iPhone OS 3

下面是用於將CGImage到CML的代碼,CML_color是矩陣結構

- (void)CGImageReftoCML:(CGImageRef)image destination:(CML_color &)dest{ 
CML_RGBA p; 
NSUInteger width=CGImageGetWidth(image); 
NSUInteger height=CGImageGetHeight(image); 
CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB(); 

unsigned char *rawData=(unsigned char*)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), image); 
CGContextRelease(context); 

int index=0; 
for (int i=0; i<height; i++) { 
    for (int j=0; j<width; j++) { 
     p.red=rawData[index++]; 
     p.green=rawData[index++]; 
     p.blue=rawData[index++]; 
     p.alpha=rawData[index++]; 
     dest(i,j)=p; 
    } 
} 

delete[] rawData; 

}

現在我想要反向函數,它將CML轉換爲CGImage。我知道所有的顏色和alpha信息來創建存儲在矩陣CML中的圖像,但我該怎麼做?

回答

3

周圍的Googling後,我終於想通了如何做到這一點我自己

下面是代碼:

- (CGImageRef)CMLtoCGImage:(CML_color &)source{ 
    int imageWidth=source.Width(); 
    int imageHeight=source.Height(); 
    char* rgba=(char*)malloc(imageWidth*imageHeight*4); 

    for (int i=0; i<imageHeight; i++) { 
     for (int j=0; j<imageWidth; j++) { 
      rgba[4*(i*imageWidth+j)]=source(i,j).red; 
      rgba[4*(i*imageWidth+j)+1]=source(i,j).green; 
      rgba[4*(i*imageWidth+j)+2]=source(i,j).blue; 
      rgba[4*(i*imageWidth+j)+3]=source(i,j).alpha; 
     } 
    } 

    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB(); 
    CGContextRef bitmapContext=CGBitmapContextCreate(rgba, imageWidth, imageHeight, 8, 4*imageWidth, colorSpace, kCGImageAlphaNoneSkipLast); 
    CFRelease(colorSpace); 

    CGImageRef cgImage=CGBitmapContextCreateImage(bitmapContext); 
    free(rgba); 

    return cgImage; 
} 
+0

你可以不用中間CGBitmapContext,這將是更有效,因爲CGBitmapContextCreateImage複製像素。 – drawnonward 2010-05-14 17:51:48