Search code examples
objective-ccocoansimage

How to create and store a new image file in cocoa


I want to create and store a empty white image file on the disk. As I am new to cocoa I don't know how to do it.


Solution

  • I see, your question is related to Mac as you have added cocoa and NSImage tags. So try this.

        NSRect kRect = NSMakeRect(0,0,100,100);
        NSView *view = [[NSView alloc] initWithFrame:kRect];
    
        CALayer *viewLayer = [CALayer layer];
        [viewLayer setBackgroundColor:CGColorCreateGenericRGB(1, 0.0, 0.0, 1)]; //RGB plus Alpha Channel
        [view setWantsLayer:YES]; // view's backing store is using a Core Animation Layer
        [view setLayer:viewLayer];
    
    //    [self.window.contentView addSubview:view];
    
        NSBitmapImageRep* kRep = [view bitmapImageRepForCachingDisplayInRect:kRect];
        [view cacheDisplayInRect:kRect toBitmapImageRep:kRep];
    
        NSData* kData = [kRep representationUsingType:NSPNGFileType properties:nil];
        [kData writeToFile:@"/Users/MyName/Desktop/red.png" atomically:YES];