私の Cocoa アプリケーションでは、ディスクから .jpg ファイルをロードして操作します。次に、.png ファイルとしてディスクに書き込む必要があります。どうやってそれができる?
ご協力いただきありがとうございます!
私の Cocoa アプリケーションでは、ディスクから .jpg ファイルをロードして操作します。次に、.png ファイルとしてディスクに書き込む必要があります。どうやってそれができる?
ご協力いただきありがとうございます!
使用CGImageDestination
して渡すkUTTypePNG
のが正しいアプローチです。ここに簡単なスニペットがあります:
@import MobileCoreServices; // or `@import CoreServices;` on Mac
@import ImageIO;
BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
if (!destination) {
NSLog(@"Failed to create CGImageDestination for %@", path);
return NO;
}
CGImageDestinationAddImage(destination, image, nil);
if (!CGImageDestinationFinalize(destination)) {
NSLog(@"Failed to write image to %@", path);
CFRelease(destination);
return NO;
}
CFRelease(destination);
return YES;
}
ImageIO
プロジェクトにand CoreServices
(またはMobileCoreServices
iOS の場合)を追加し、ヘッダーを含める必要があります。
iOS を使用していて、Mac でも動作するソリューションが必要ない場合は、より簡単な方法を使用できます。
// `image` is a CGImageRef
// `path` is a NSString with the path to where you want to save it
[UIImagePNGRepresentation([UIImage imageWithCGImage:image]) writeToFile:path atomically:YES];
私のテストでは、ImageIO アプローチは、iPhone 5s での UIImage アプローチよりも約 10% 高速でした。シミュレーターでは、UIImage アプローチの方が高速でした。パフォーマンスに本当に関心がある場合は、デバイスの特定の状況でそれぞれをテストする価値があるでしょう。
これは、macOS に適した Swift 3 & 4 の例です。
@discardableResult func writeCGImage(_ image: CGImage, to destinationURL: URL) -> Bool {
guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else { return false }
CGImageDestinationAddImage(destination, image, nil)
return CGImageDestinationFinalize(destination)
}
を作成し、作成するファイルのタイプとしてCGImageDestination
渡します。kUTTypePNG
画像を追加し、宛先を確定します。