如何使用Objective C将.jpg图像转换为.bmp格式?

时间:2010-03-03 09:18:56

标签: iphone objective-c

任何人都知道如何使用objective-C在iphone中将.jpg图像转换为.bmp格式? 以及我如何处理(或RGB颜色)iPhone设备捕获图像的每个像素? 是否需要转换图像类型?

2 个答案:

答案 0 :(得分:0)

您将无法轻松获得iPhone上的bmp表示。在Mac上的Cocoa中,它由NSBitmapImageRep类管理,并且非常简单,如下所述。

在较高级别,您需要将.jpg放入NSBitmapImageRep对象,然后让框架为您处理转换:

一个。将JPG图像转换为NSBitmapImageRep

湾使用内置的NSBitmapImageRep方法以所需格式保存。

NSBitmapImageRep *origImage = [self documentAsBitmapImageRep:[NSURL fileURLWithPath:pathToJpgImage]];
NSBitmapImageRep *bmpImage = [origImage representationUsingType:NSBMPFileType properties:nil];

- (NSBitmapImageRep*)documentAsBitmapImageRep:(NSURL*)urlOfJpg;
{

    CIImage *anImage = [CIImage imageWithContentsOfURL:urlOfJpg];
    CGRect outputExtent = [anImage extent];

    // Create a new NSBitmapImageRep.
    NSBitmapImageRep *theBitMapToBeSaved = [[NSBitmapImageRep alloc]  
                                            initWithBitmapDataPlanes:NULL pixelsWide:outputExtent.size.width  
                                            pixelsHigh:outputExtent.size.height  bitsPerSample:8 samplesPerPixel:4  
                                            hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace  
                                            bytesPerRow:0 bitsPerPixel:0];

    // Create an NSGraphicsContext that draws into the NSBitmapImageRep.  
    NSGraphicsContext *nsContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:theBitMapToBeSaved];

    // Save the previous graphics context and state, and make our bitmap context current.
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext: nsContext];
    CGPoint p = CGPointMake(0.0, 0.0);

    // Get a CIContext from the NSGraphicsContext, and use it to draw the CIImage into the NSBitmapImageRep.
    [[nsContext CIContext] drawImage:anImage atPoint:p fromRect:outputExtent];

    // Restore the previous graphics context and state.
    [NSGraphicsContext restoreGraphicsState];

    return [[theBitMapToBeSaved retain] autorelease];

}

在iPhone上,UIKit不直接支持BMP,因此您必须自己下载Quartz/Core Graphics并自行管理转换。

逐像素处理涉及更多。同样,如果这对您来说是一项艰难的要求,您应该非常熟悉设备上的核心图形功能。

答案 1 :(得分:0)

  1. 将JPG图像加载到UIImage,它可以原生处理。
  2. 然后你可以从UIImage对象中获取CGImageRef
  3. 创建一个新的位图CG图像上下文,其具有与您已有图像相同的属性,并提供您自己的数据缓冲区来保存位图上下文的字节。
  4. 将原始图像绘制到新的位图上下文中:您提供的缓冲区中的字节现在是图像的像素。
  5. 现在您需要对实际的BMP文件进行编码,该文件不是UIKit或CoreGraphics(据我所知)框架中存在的功能。幸运的是,它是一种有意无关紧要的格式 - 我在一小时或更短的时间内为BMP编写了快速而肮脏的编码器。这是规范:http://www.fileformat.info/format/bmp/egff.htm(版本3应该没问题,除非你需要支持alpha,但你可能不支持。)
  6. 祝你好运。