我正在对图像进行一些操作,完成后,我想将图像以 PNG 格式保存在磁盘上。我正在执行以下操作:
+ (void)saveImage:(NSImage *)image atPath:(NSString *)path {
[image lockFocus] ;
NSBitmapImageRep *imageRepresentation = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0.0, 0.0, image.size.width, image.size.height)] ;
[image unlockFocus] ;
NSData *data = [imageRepresentation representationUsingType:NSPNGFileType properties:nil];
[data writeToFile:path atomically:YES];
}
这段代码可以工作,但在配备 Retina 屏幕的 Mac 上存在问题;如果我打印NSBitmapImageRep
对象,我得到一个不同大小和像素的矩形,当我的图像保存在磁盘上时,它的大小是原来的两倍:
$0 = 0x0000000100413890 NSBitmapImageRep 0x100413890 Size={300, 300} ColorSpace=sRGB IEC61966-2.1 colorspace BPS=8 BPP=32 Pixels=600x600 Alpha=YES Planar=NO Format=0 CurrentBacking=<CGImageRef: 0x100414830>
我试图强制像素大小不关心视网膜比例,因为我想保留原始大小:
imageRepresentation.pixelsWide = image.size.width;
imageRepresentation.pixelsHigh = image.size.height;
这次我在打印时得到了正确的尺寸NSBitmapImageRep
对象,但是当我保存文件时,我仍然遇到同样的问题:
$0 = 0x0000000100413890 NSBitmapImageRep 0x100413890 Size={300, 300} ColorSpace=sRGB IEC61966-2.1 colorspace BPS=8 BPP=32 Pixels=300x300 Alpha=YES Planar=NO Format=0 CurrentBacking=<CGImageRef: 0x100414830>
知道如何解决这个问题并保留原始像素大小吗?