Converting between multiple image formats in Objective-C

后端 未结 2 1819
傲寒
傲寒 2020-12-19 09:19

I want to be able to, being given a path to an image, convert that image into another image, but with a different format. By format I mean .png, .bmp .jpg .tiff, etc. In pse

相关标签:
2条回答
  • 2020-12-19 09:33

    Exploring outward from NSImage leads you to NSBitmapImageRep, which does exactly what you want.

    Some of those iPhone questions are relevant as well, because the solution that works on both platforms (and the implementation behind the NSBitmapImageRep solution nowadays) is to use CGImageSource to read in the image and CGImageDestination to write it out.

    0 讨论(0)
  • 2020-12-19 09:50

    Allright, so with Peter's help I could figure this out. First, if you're working with image paths, then open directly the file with NSData like so:

    NSData* imgData = [NSData dataWithContentsOfFile: filePath];
    

    If you're working with NSImage objects and is difficult for you to have the path (for example with an NSImageView) then do this (image is the NSImage object you have):

    NSData* imgData = [image TIFFRepresentation];
    

    Now that you have your image into NSData objects, get it into a NSBitmapImageRep:

    NSBitmapImageRep* bitmap = [NSBitmapImageRep imageRepWithData: imgData];
    

    And then get a new NSData object, but with a different format:

    NSData* newData = [bitmap representationUsingType: NSPNGFileType properties: nil];
    // I used NSPNGFileType as an example, but all the
    // types I wanted to convert between (except PDF) are supported
    

    Finally, save that newData into a file:

    [newData writeToFile: newPath atomically: YES]
    

    Simple as pie, once you get how it works!


    The support for transparency and size control is not that difficult either:

    • The NSImage class provides support for setting image's size (-setSize:)
    • The NSImageRep (superclass of NSBitmapImageRep) has the -setAlpha: method

    Just call those when you need. +1 for Cocoa!

    0 讨论(0)
提交回复
热议问题