gpt4 book ai didi

objective-c - 将 CGImageRef 保存为 PNG 文件时出错? (电弧引起的?)

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

这段代码曾经可以工作,但我认为 Xcode 的新 ARC 可能已经杀死了它

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
CGDirectDisplayID displayID = CGMainDisplayID();
CGImageRef image = CGDisplayCreateImage(displayID); //this is a screenshot (works fine)
[self savePNGImage:image path:@"~/Desktop"];
}


-(void)savePNGImage:(CGImageRef)imageRef path:(NSString *)path {
NSURL *outURL = [[NSURL alloc] initFileURLWithPath:path];
//here xcode suggests using __bridge for CFURLRef?
CGImageDestinationRef dr = CGImageDestinationCreateWithURL ((__bridge CFURLRef)outURL, (CFStringRef)@"public.png" , 1, NULL);
CGImageDestinationAddImage(dr, imageRef, NULL);
CGImageDestinationFinalize(dr);
}

此代码返回错误:

ImageIO: CGImageDestinationAddImage image destination parameter is nil

我认为这意味着 CGImageDestinationRef 没有正确创建。我一直无法找到新的 Xcode 不会给出相同错误的实现,我做错了什么?

最佳答案

无论有没有 ARC,您发布的代码都无法工作,因为您需要在传递路径名之前扩展路径名中的波浪号。

您发布的代码还泄漏了 CGDisplayCreateImageCGImageDestinationCreateWithURL 返回的项目。这是一个有效且不会泄漏的示例:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
CGDirectDisplayID displayID = CGMainDisplayID();
CGImageRef imageRef = CGDisplayCreateImage(displayID); //this is a screenshot (works fine)

NSString *path = [@"~/Desktop/public.png" stringByExpandingTildeInPath];
[self savePNGImage:imageRef path:path];

CFRelease(imageRef);
}

- (void)savePNGImage:(CGImageRef)imageRef path:(NSString *)path
{
NSURL *fileURL = [NSURL fileURLWithPath:path];
CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypePNG , 1, NULL);

CGImageDestinationAddImage(dr, imageRef, NULL);
CGImageDestinationFinalize(dr);

CFRelease(dr);
}

关于objective-c - 将 CGImageRef 保存为 PNG 文件时出错? (电弧引起的?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8225838/

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