将CGImageRef保存为PNG文件错误? (ARC导致?) [英] Save CGImageRef to PNG file errors? (ARC Caused?)

查看:305
本文介绍了将CGImageRef保存为PNG文件错误? (ARC导致?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This code used to work, however I think Xcode's new ARC may have killed it

- (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

ImageIO: CGImageDestinationAddImage image destination parameter is nil

表示未正确创建CGImageDestinationRef。我不能找到一个实现,新的Xcode不会给出相同的错误,我做错了什么?

which I assume means the CGImageDestinationRef is not being created correctly. I haven't been able to find an implementation of this that the new Xcode doesn't give the same error for, what am I doing wrong?

推荐答案

您发布的代码在使用或不使用ARC时将无法工作,因为您需要在传递之前先扩展路径名称中的波浪号。

The code you posted wouldn't work either with or without ARC, because you need to expand the tilde in the path name before passing it.

您发布的代码也泄漏了 CGDisplayCreateImage CGImageDestinationCreateWithURL 返回的项目。这里有一个工作和不泄漏的示例:

The code you posted also was leaking the items returned by CGDisplayCreateImage and CGImageDestinationCreateWithURL. Here's an example that works and doesn't leak:

- (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);
}

这篇关于将CGImageRef保存为PNG文件错误? (ARC导致?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆