Intelligent Technology's Technical Blog

株式会社インテリジェントテクノロジーの技術情報ブログです。

【iOS】「え?これだけ?」TIFF画像作成

こんにちは、野口です。

iOSで画像を作成する時、JPEGPNGならUIImageJPEGRepresentationやUIImagePNGRepresentationのように簡易APIが用意されています。しかし、TIFF(orその他フォーマット)では、簡易APIが用意されていませんので、JPEGPNG以外のフォーマットの画像を作成する方法を紹介したいと思います。

CGImageDestination

CGImageDestinationを使用します。

CGImageDestination Reference

サンプルコード

#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/UTCoreTypes.h>


- (NSData *)makeTiffImage:(UIImage *)image {

    NSMutableData *tiffData = [NSMutableData data];

    // 画像の保存先を作成
    CGImageDestinationRef destination = CGImageDestinationCreateWithData ( (CFMutableDataRef)tiffData , kUTTypeTIFF, 1, null);

    // オプションの設定。指定しない場合はnull。
    // 圧縮方式を指定( 1=no compression, 5=LZW,  32773=PackBits)
    CFDictionaryRef options = (CFDictionaryRef)@{(NSString *) kCGImagePropertyTIFFDictionary:@{(NSString *)kCGImagePropertyTIFFCompression:@5}}

    // 画像を追加
    CGImageDestinationAddImage(destination, image.CGImage, options );

    // 作成した画像を保存先へ保存
    CGImageDestinationFinalize(destination);

    CFRelease(destination);

    return tiffData;
}

今回はNSMutableDataに保存するので、

 CGImageDestinationRef CGImageDestinationCreateWithData ( CFMutableDataRef data, CFStringRef type, size_t count, CFDictionaryRef options ); 

を使用していますが、別の保存形式を指定したい場合は以下のメソッドを使用することができます。

 CGImageDestinationRef CGImageDestinationCreateWithDataConsumer ( CGDataConsumerRef consumer, CFStringRef type, size_t count, CFDictionaryRef options ); 

 CGImageDestinationRef CGImageDestinationCreateWithURL ( CFURLRef url, CFStringRef type, size_t count, CFDictionaryRef options ); 

第1引数には作成した画像の保存先、第2引数には保存する画像のフォーマット、第3引数に使用する画像の枚数、第4引数にオプションを設定できます。

第2引数に指定する画像のフォーマットは以下のものを指定できます。

 const CFStringRef kUTTypeImage;
 const CFStringRef kUTTypeJPEG;
 const CFStringRef kUTTypeJPEG2000;
 const CFStringRef kUTTypeTIFF;
 const CFStringRef kUTTypePICT;
 const CFStringRef kUTTypeGIF;
 const CFStringRef kUTTypePNG;
 const CFStringRef kUTTypeQuickTimeImage;
 const CFStringRef kUTTypeAppleICNS;
 const CFStringRef kUTTypeBMP;
 const CFStringRef kUTTypeICO;
 const CFStringRef kUTTypeRawImage;
 const CFStringRef kUTTypeScalableVectorGraphics;

CGImageDestinationAddImageで画像を追加していますが、第3引数でオプションを指定できます。
指定できるオプションは以下のリファレンスをご参照ください。

CGImageProperties Reference

終わりに

以上のようにJPEGPNG程ではないですが、iOSでも比較的簡単にTIFFの画像を作成できます。もし、iOSTIFF(orその他フォーマット)の画像を作成する必要が出てきたときに参考にしてみてください。

以上です。