Convert bitmap image information into CGImage in iPhone OS 3

只谈情不闲聊 提交于 2020-01-15 09:31:29

问题


I want to create a CGImage with the color information I already have

Here is the code for converting the CGImage to CML, CML_color is a matrix structure

- (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;

}

Now I want the reverse function, which converts CML into CGImage. I know all the color and alpha information to create the image, which stored in the matrix CML, but how can I do that?


回答1:


After Googling around I finally figured out how to do this myself

Here is the code:

- (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;
}


来源:https://stackoverflow.com/questions/2825235/convert-bitmap-image-information-into-cgimage-in-iphone-os-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!