41

私の Cocoa アプリケーションでは、ディスクから .jpg ファイルをロードして操作します。次に、.png ファイルとしてディスクに書き込む必要があります。どうやってそれができる?

ご協力いただきありがとうございます!

4

4 に答える 4

111

使用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(またはMobileCoreServicesiOS の場合)を追加し、ヘッダーを含める必要があります。


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 アプローチの方が高速でした。パフォーマンスに本当に関心がある場合は、デバイスの特定の状況でそれぞれをテストする価値があるでしょう。

于 2011-10-05T22:08:19.260 に答える
33

これは、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)
}
于 2016-11-02T02:35:04.253 に答える
23

を作成し、作成するファイルのタイプとしてCGImageDestination渡します。kUTTypePNG画像を追加し、宛先を確定します。

于 2009-08-24T09:40:04.140 に答える