【发布时间】:2011-10-18 08:26:58
【问题描述】:
基本上,我正在尝试创建一个用于批量图像处理的程序,该程序将调整每个图像的大小并在边缘周围添加边框(边框也将由图像组成)。尽管我还没有实现那个实现,这超出了我的问题的范围,但我问它是因为即使我在这里得到了很好的答案,我仍然可能采取了错误的方法来实现这一点,以及任何有助于认识到这一点的方法将不胜感激。无论如何,这是我的问题:
问题: 我可以使用下面的现有代码并对其进行修改以创建比当前输出的代码更高质量的图像保存到文件吗?我真的花了 10 多个小时试图找出我做错了什么; “secondaryImage”将高质量的调整大小的图像绘制到自定义视图中,但我为保存文件所做的一切都导致图像质量大大降低(没有那么多像素化,只是明显更模糊)。最后,我在 Apple 的“Reducer”示例(ImageReducer.m 的末尾)中找到了一些代码,它锁定了焦点并从当前视图中获取 NSBitmapImageRep。这使得图像质量显着提高,但是,Photoshop 执行相同操作的输出更清晰一些。看起来绘制到视图的图像与保存到文件的质量相同,因此两者都低于 Photoshop 将同一图像调整为 50% 的质量,就像这张一样。是否有可能获得比这更高质量的调整大小的图像?
除此之外,如何修改现有代码以控制保存到文件的图像质量?我可以更改压缩和像素密度吗?对于修改我的代码或向我指出好的示例或教程(最好是后者)的任何帮助,我将不胜感激。非常感谢!
- (void)drawRect:(NSRect)rect {
// Getting source image
NSImage *image = [[NSImage alloc] initWithContentsOfFile: @"/Users/TheUser/Desktop/4.jpg"];
// Setting NSRect, which is how resizing is done in this example. Is there a better way?
NSRect halfSizeRect = NSMakeRect(0, 0, image.size.width * 0.5, image.size.height * 0.5);
// Sort of used as an offscreen image or palate to do drawing onto; the future I will use to group several images into one.
NSImage *secondaryImage = [[NSImage alloc] initWithSize: halfSizeRect.size];
[secondaryImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation: NSImageInterpolationHigh];
[image drawInRect: halfSizeRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0];
[secondaryImage unlockFocus];
[secondaryImage drawInRect: halfSizeRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0];
// Trying to add image quality options; does this usage even affect the final image?
NSBitmapImageRep *bip = nil;
bip = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide: secondaryImage.size.width pixelsHigh: secondaryImage.size.width bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
[secondaryImage addRepresentation: bip];
// Four lines below are from aforementioned "ImageReducer.m"
NSSize size = [secondaryImage size];
[secondaryImage lockFocus];
NSBitmapImageRep *bitmapImageRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, size.width, size.height)];
[secondaryImage unlockFocus];
NSDictionary *prop = [NSDictionary dictionaryWithObject: [NSNumber numberWithFloat: 1.0] forKey: NSImageCompressionFactor];
NSData *outputData = [bitmapImageRep representationUsingType:NSJPEGFileType properties: prop];
[outputData writeToFile:@"/Users/TheUser/Desktop/4_halfsize.jpg" atomically:NO];
// release from memory
[image release];
[secondaryImage release];
[bitmapImageRep release];
[bip release];
}
【问题讨论】:
-
我应该提一下我之前使用的导致图像质量差得多的代码。我没有锁定焦点并从 initWithFocusedView 初始化 NSBitmapImageRep,而是在做我在网上无数其他地方看到的事情,聚焦后从被绘制的 secondaryImage 释放,使用以下内容将 secondaryImage 写入文件:
NSData *imageData = [[secondaryImage TIFFRepresentation] representationUsingType: NSJPEGFileType properties: nil];@987654323 @
标签: objective-c cocoa nsimage