我正在对图像进行一些操作,在完成之后,我想将图像保存为磁盘上的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];
}
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常,但问题出在视网膜mac上,如果我打印NSBitmapImageRep对象,我得到一个不同的大小和像素rect,当我的图像保存在磁盘上时,它的大小是两倍:
$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>
Run Code Online (Sandbox Code Playgroud)
因为我想要保留原始大小,我强制像素大小不要关心视网膜比例:
imageRepresentation.pixelsWide = image.size.width;
imageRepresentation.pixelsHigh = image.size.height;
Run Code Online (Sandbox Code Playgroud)
这次我在打印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>
Run Code Online (Sandbox Code Playgroud)
知道如何解决这个问题,并保留原始像素大小?
macos nsimage image-resizing nsbitmapimagerep retina-display
我得到的图像只有一个表示,那是一个NSCGImageSnapshotRep.
我试过[NSCGImageSnapshotRep bitmapData]但是,班级没有选择器bitmapData.
有人知道这堂课吗?我该bitmapData怎么办?
我从Webkit获得了这个NSImage [DOMElement renderedImage].
正确的用法是[NSBitmapImageRep representationUsingType:id properties:id],这种方法在这种情况下不起作用.
我也没多想compatibily,我会很高兴找到一个解决方案10.5+或10.6以上版本.