这段代码以前有用,但我认为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图像目的地 参数是nil
我认为这意味着没有正确创建CGImageDestinationRef。我无法找到一个这样的实现,新的Xcode没有给出相同的错误,我做错了什么?
答案 0 :(得分:4)
您发布的代码无论是否使用ARC都无法使用,因为您需要在传递代码之前展开路径名中的代字号。
您发布的代码也泄漏了CGDisplayCreateImage
和CGImageDestinationCreateWithURL
返回的项目。这是一个有效且无泄漏的例子:
- (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);
}