使用 NSAffineTransform 轮换 NSImage 会生成两倍大小的文件



我使用以下代码翻转(旋转 180 度)NSImage.但是,新映像的大小(MB,而不是尺寸)是保存到磁盘时的原始映像的两倍。我希望它与原始版本大致相同。我怎样才能做到这一点?

NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:[[_imageView image] TIFFRepresentation]];
NSImage *img = [[NSImage alloc] initWithSize:NSMakeSize(imageRep.pixelsWide, imageRep.pixelsHigh)];
[img lockFocus];
NSAffineTransform *rotator = [NSAffineTransform transform];
[rotator translateXBy:imageRep.pixelsWide yBy:imageRep.pixelsHigh];
[rotator scaleXBy:-1 yBy:-1];
[rotator concat];
[imageRep drawInRect:NSMakeRect(0, 0, imageRep.pixelsWide, imageRep.pixelsHigh)];
[img unlockFocus];

我用来将图像保存到磁盘的代码:

[[NSFileManager defaultManager] createFileAtPath:path contents:[img TIFFRepresentation] attributes:nil];

提前感谢!

我仍然不知道造成这种情况的根本原因,但一种解决方法是保存到 JPEG 表示而不是 TIFF。我写的方法如下:

- (void)CompressAndSaveImg:(NSImage *)img ToDiskAt:(NSString *)path WithCompressionFactor:(float)value{
    NSData *imgData = [img TIFFRepresentation];
    NSBitmapImageRep *imgRep = [NSBitmapImageRep imageRepWithData:imgData];
    NSNumber *compressionFactor = [NSNumber numberWithFloat:value];
    NSDictionary *imageProps = [NSDictionary dictionaryWithObject:compressionFactor forKey:NSImageCompressionFactor];
    imgData = [imgRep representationUsingType:NSJPEGFileType properties:imageProps];
    [imgData writeToFile:path atomically:YES];
}

您可以使用 WithCompressionFactor:(float)value 参数,但0.75对我来说效果很好。

最新更新