这段代码(source
是一个带有NSImage
对象的NSMutableArray
:
NSURL *fileURL = [NSURL fileURLWithPath:aPath]; CGImageDestinationRef dr = CGImageDestinationCreateWithURL((CFURLRef)fileURL, kUTTypeAppleICNS, 1, NULL); for (NSImage *img in source) { NSLog(@"%@",img); CGImageRef i1 = [img CGImageForProposedRect:NULL context:nil hints:nil]; CGImageDestinationAddImage(dr, i1, NULL); } CGImageDestinationFinalize(dr); CFRelease(dr);
产生以下输出:
2012-12-26 13:48:57.682 Eicon[1131:1b0f] |NSImage 0x1025233b0 Size={11.52, 11.52} Reps=( "NSBitmapImageRep 0x10421fc30 Size={11.52, 11.52} ColorSpace=(not yet loaded) BPS=8 BPP=(not yet loaded) Pixels=1024x1024 Alpha=NO Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x104221170"
(...) <- here the other NSImage instances are logged.
ImageIO: |ERROR| CGImageDestinationFinalize image destination does not have enough images
你知道为什么最后会出现错误吗? (顺便说一句,我想过使用 IconFamily 来代替,但它使用的很多方法已被弃用)。
编辑:也许更重要的是提及我用来生成图像的代码,如果该代码有问题我不会感到惊讶(我是菜鸟):
// Get images
[source removeAllObjects];
NSSize sizes[10];
sizes[0] = NSMakeSize(1024,1024);
sizes[1] = NSMakeSize(512,512);
sizes[2] = NSMakeSize(512,512);
sizes[3] = NSMakeSize(256,256);
sizes[4] = NSMakeSize(256,256);
sizes[5] = NSMakeSize(128,128);
sizes[6] = NSMakeSize(64,64);
sizes[7] = NSMakeSize(32,32);
sizes[8] = NSMakeSize(32,32);
sizes[9] = NSMakeSize(16,16);
for (int i=0 ; i<10 ; i++) {
if ([[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"Size%i",i+1]]) {
NSBitmapImageRep *srcimg = [[NSBitmapImageRep alloc] initWithData:[NSData dataWithContentsOfFile:aFile]];
[srcimg setPixelsHigh:sizes[i].height];
[srcimg setPixelsWide:sizes[i].width];
NSImage *newimg = [[NSImage alloc] initWithSize:NSZeroSize];
[newimg addRepresentation:srcimg];
if (![newimg isValid]) {
[delegate error:@"Invalid file."];
}
else [source addObject:newimg];
}
}
最佳答案
一部分猜测解决方案,一部分进行更改以改进代码,即使它不是解决方案......
CGImageDestinationCreateWithURL
中的图像数量错误;您应该传递您希望添加的图像数量。
给定一个循环,您显然希望添加一个或多个。。根据您的输出,您实际上添加了不止一张图像。
您说过要添加恰好 1 张图像,然后您添加了不止一张图像。
我的猜测是错误消息不清楚/过于具体。错误提示:
CGImageDestinationFinalize image destination does not have enough images
但我认为这意味着:
CGImageDestinationFinalize image destination has a different number of images than you promised
换句话说,问题不在于您提供的图像少于;而是您提供的图像少于预期。而是您提供的比预期多,并且 CGImageDestination 不区分多与少。
更改您的 CGImageDestinationCreateWithURL
调用以提供您要添加的正确数量的图像。鉴于您问题中的代码,这应该是 source.count
。
关于macos - 创建 ICNS 文件时出现 ImageIO 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14040938/