gpt4 book ai didi

swift - 将 CGImageRef 保存到 png 文件?

转载 作者:行者123 更新时间:2023-12-03 16:00:59 28 4
gpt4 key购买 nike

在我的 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;
}

您需要将 ImageIOCoreServices(或 iOS 上的 MobileCoreServices)添加到您的项目中并包含 header 。

<小时/>

如果您使用的是 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];

在我的测试中,在我的 iPhone 5s 上,ImageIO 方法比 UIImage 方法快约 10%。在模拟器中,UIImage 方法更快。如果您确实关心性能,那么可能值得针对您在设备上的特定情况进行测试。

关于swift - 将 CGImageRef 保存到 png 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1320988/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com