Сохранить CGImageRef в PNG файл? (ARC вызвал?)
Этот код работал, однако я думаю, что новый ARC XCode, возможно, убил его
- (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 - ноль
что я предполагаю, означает, что CGImageDestinationRef не создается правильно. Я не смог найти реализацию этого, что новый Xcode не дает ту же ошибку, что я делаю неправильно?
1 ответ
Решение
Размещенный вами код не будет работать ни с 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);
}