How to create a ICNS icon programmatically?

▼魔方 西西 提交于 2020-01-01 14:22:07

问题


OK this is what I want :

  • Take some NSImages
  • Add them to an ICNS file
  • Save it

This is what I've done so far (purely as a test) :

- (CGImageRef)refFromImage:(NSImage*)img
{
    CGImageSourceRef source;

    source = CGImageSourceCreateWithData((CFDataRef)[img TIFFRepresentation], NULL);
    CGImageRef maskRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);

    return maskRef;
}

- (void)awakeFromNib
{
    NSImage* img1 = [NSImage imageNamed:@"image1"];
    NSImage* img2 = [NSImage imageNamed:@"image2"];

    NSLog(@"%@",img1);
    CGImageRef i1 = [self refFromImage:img1];
    CGImageRef i2 = [self refFromImage:img2];

    NSURL *fileURL = [NSURL fileURLWithPath:[@"~/Documents/final.icns" stringByExpandingTildeInPath]]; 
    CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeAppleICNS , 1, NULL);

    CGImageDestinationAddImage(dr, i1, NULL);
    CGImageDestinationAddImage(dr, i2, NULL);
    /* Even tried adding 'multiple' times

    CGImageDestinationAddImage(dr, i1, NULL);
    CGImageDestinationAddImage(dr, i2, NULL);
    CGImageDestinationAddImage(dr, i1, NULL);
    CGImageDestinationAddImage(dr, i2, NULL);

    */

    CGImageDestinationFinalize(dr);

    CFRelease(dr);
}

But, it still keeps throwing an error :

ImageIO: CGImageDestinationFinalize image destination does not have enough images

What's wrong with my code?


I've had a look at the answers below, but still nothing :

  • Save CGImageRef to PNG file errors? (ARC Caused?)
  • How exactly to make a CGImageRef from an image on disk

回答1:


You can use IconFamily.

IconFamily is a Cocoa/Objective-C wrapper for the Mac OS X Carbon API's "icon family" data type. Its main purpose is to enable Cocoa applications to easily create custom file icons from NSImage instances, and thus take advantage of Mac OS X's high-resolution RGBA "thumbnail" icon formats to provide richly detailed thumbnail previews of the files' contents.

NSImage *mImage = [[NSImage alloc] initWithContentsOfFile:@"/Users/Username/Desktop/WhiteTiger.jpg"];
IconFamily *fam = [IconFamily iconFamilyWithThumbnailsOfImage:mImage];    
[fam writeToFile:@"/Users/Username/Desktop/WhiteTiger.icns"];


来源:https://stackoverflow.com/questions/12315162/how-to-create-a-icns-icon-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!