1. 程式人生 > >How to save PNG file from NSImage (retina issues)

How to save PNG file from NSImage (retina issues)

參考網址:https://stackoverflow.com/questions/17507170/how-to-save-png-file-from-nsimage-retina-issues 

/**
 儲存指定大小圖片到本地路徑下

 @param image image 實體
 @param filePath 檔案的絕對路徑
 @param size imageSize (畫素大小)
 @return 是否成功
 */
+ (BOOL)saveImage:(NSImage *)image andFilePath:(NSString *)filePath andSize:(CGSize)size {
  
    NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
                             initWithBitmapDataPlanes:NULL
                             pixelsWide:size.width
                             pixelsHigh:size.height
                             bitsPerSample:8
                             samplesPerPixel:4
                             hasAlpha:YES
                             isPlanar:NO
                             colorSpaceName:NSCalibratedRGBColorSpace
                             bytesPerRow:0
                             bitsPerPixel:0];
    [rep setSize:NSMakeSize(size.width, size.height)];
    
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:[NSGraphicsContext     graphicsContextWithBitmapImageRep:rep]];
    [image drawInRect:NSMakeRect(0, 0, size.width, size.height)  fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
    [NSGraphicsContext restoreGraphicsState];
    
    NSData *data = [rep representationUsingType:NSBitmapImageFileTypePNG properties:nil];
    
    return [data writeToFile:filePath atomically:YES];
}