【问题标题】:Using NSAffineTransform to rotate NSImage results in a file twice the size使用 NSAffineTransform 旋转 NSImage 会产生两倍大小的文件
【发布时间】:2015-01-19 22:12:17
【问题描述】:

我正在使用以下代码翻转(旋转 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];

提前致谢!

【问题讨论】:

  • TIFF 有图像压缩选项,也许这就是问题所在。
  • 源图像也是TIFF吗? TIFF 是一种漂亮的图像格式,但与 JPEG 或 PNG 相比非常冗长,所以这可能是问题所在。

标签: objective-c cocoa nsimage image-rotation nsaffinetransform


【解决方案1】:

我仍然不知道其根本原因,但一种解决方法是保存为 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 对我来说很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2015-02-08
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多