4

I have managed to get OpenJPEG to compile in my iOS app, but I have no clue where to begin trying to convert a UIImage to a J2K file or J2K in memory buffer. Suggestions?

jjxtra
  • 20,415
  • 16
  • 100
  • 140
  • J2K? You want to save a Jpeg 2000 file? I've done that in Mac OS, but not in iOS. Poking around in the docs a little bit I think you'd have to create a CGImageDestination and give it a type of kUTTypeJPEG2000. – Duncan C Nov 03 '13 at 04:14
  • @DuncanC This worked amazingly well and resulted in a way smaller image than JPG with transparency preserved. Thanks so much for pointing me to that. – jjxtra Nov 04 '13 at 17:31

1 Answers1

4

Apparently ImageIO can do this. You'll need to add image io framework to your project and then this code is working for me:

#import <ImageIO/ImageIO.h> // or @import ImageIO if modules enabled
#import <MobileCoreServices/MobileCoreServices.h>

// ...    

// quality is 0-1 (0 = smallest file size, 1 = lossless quality)
+ (NSData*) convertToJPEG2000:(UIImage*)image withQuality:(float)quality
{
    NSMutableData* d = [NSMutableData data];
    CGImageDestinationRef destinationRef = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)d, kUTTypeJPEG2000, 1, NULL);
    CGImageDestinationSetProperties(destinationRef, NULL);
    CGImageDestinationAddImage(destinationRef, image.CGImage, (__bridge CFDictionaryRef)@{ (NSString*)kCGImageDestinationLossyCompressionQuality: @(quality) });

    if (!CGImageDestinationFinalize(destinationRef))
    {
        d = nil;
    }
    CFRelease(destinationRef);

    return d;
}
jjxtra
  • 20,415
  • 16
  • 100
  • 140
  • Last time I checked, iOS did not support `kUTTypeJPEG2000`. The type identifier constant was present but encoding did not work. Which version of iOS did you try? – Nikolai Ruhe Dec 02 '13 at 20:53
  • This is working on iOS 5+. Haven't tested earlier iOS versions. – jjxtra Dec 02 '13 at 21:21
  • Looks like it's supported on iOS 3+ - extern const CFStringRef kUTTypeJPEG2000 __OSX_AVAILABLE_STARTING(__MAC_10_4,__IPHONE_3_0); – jjxtra Dec 02 '13 at 21:23
  • on iOS 7 you need import in order to use kUTTypeJPEG2000 . – Gonzalo Bahamondez May 13 '14 at 13:30
  • @PsychoDad do you know if converting to jpeg2000 as slow as it used to be? Or has the performance gotten better with newer devices/versions of iOS? – blueether Apr 09 '15 at 20:04
  • for line CGImageDestinationSetProperties(destinationRef, NULL); getting log that property is not dictionary. would it cause some issue. – Alok C Jun 25 '15 at 19:10
  • Do I have to set destination property – Alok C Jun 25 '15 at 19:43