如何在iOS中创建和检索新的位图

时间:2013-04-15 10:54:38

标签: ios objective-c uiimage bitmapimage bitmapdata

我想将图像从一种格式(.png)转换为其他图像格式(.img格式)。我能够检索和修改相同图像格式的rgba值。我还需要做些什么来将其转换为其他图像格式吗?

我创建了一个空位图,并希望将此位图绘制到图像。

CGImageRef cgimage = image.CGImage;

size_t width  = CGImageGetWidth(cgimage);
size_t height = CGImageGetHeight(cgimage);

size_t bytesPerRow = CGImageGetBytesPerRow(cgimage);
size_t bytesPerPixel = CGImageGetBitsPerPixel(cgimage);
size_t bitsPerComponent = CGImageGetBitsPerComponent(cgimage);
size_t bytes_per_pixel = bytesPerPixel / bitsPerComponent;

CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgimage);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
memset(rawData, 0, height * width * 4);

CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);

iOS中是否有任何函数用修改后的rgba值填充输出位图。

1 个答案:

答案 0 :(得分:2)

它看起来像这样:

UIImage *image = self.theImage;
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:height * width * 4];
unsigned char *rawData = data.mutableBytes;
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), imageRef);
CGContextRelease(context);

int byteIndex = (bytesPerRow * 0) + 0 * bytesPerPixel;

如果您想操纵数据,则迭代byteIndex。希望这就是你要找的东西。