How to save PNG file from NSImage (retina issues)

后端 未结 6 982
情话喂你
情话喂你 2020-11-29 01:37

I\'m doing some operations on images and after I\'m done, I want to save the image as PNG on disk. I\'m doing the following:

+ (void)saveImage:(NSImage *)ima         


        
6条回答
  •  误落风尘
    2020-11-29 02:09

    If you have an NSImage and want to save it as an image file to the filesystem, you should never use lockFocus! lockFocus creates a new image which is determined for getting shown an the screen and nothing else. Therefore lockFocus uses the properties of the screen: 72 dpi for normal screens and 144 dpi for retina screens. For what you want I propose the following code:

    + (void)saveImage:(NSImage *)image atPath:(NSString *)path {
    
       CGImageRef cgRef = [image CGImageForProposedRect:NULL
                                                context:nil
                                                  hints:nil];
       NSBitmapImageRep *newRep = [[NSBitmapImageRep alloc] initWithCGImage:cgRef];
       [newRep setSize:[image size]];   // if you want the same resolution
       NSData *pngData = [newRep representationUsingType:NSPNGFileType properties:nil];
       [pngData writeToFile:path atomically:YES];
       [newRep autorelease];
    }
    

提交回复
热议问题