objective-c - 如何在 Objective-c/Cocoa (OSX) 中做出完美的裁剪(不改变质量)

标签 objective-c macos cocoa crop nsimage

在 Objective-c/cocoa (OSX) 中有没有办法在不改变图像质量的情况下裁剪图像?

我非常接近解决方案,但我仍然可以在颜色上检测到一些差异。放大文本时我可以注意到它。这是我目前使用的代码:

    NSImage *target = [[[NSImage alloc]initWithSize:panelRect.size] autorelease];
    target.backgroundColor = [NSColor greenColor];
    //start drawing on target
    [target lockFocus];
    [NSGraphicsContext saveGraphicsState];
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationNone];
    [[NSGraphicsContext currentContext] setShouldAntialias:NO];

    //draw the portion of the source image on target image
    [source drawInRect:NSMakeRect(0,0,panelRect.size.width,panelRect.size.height)
              fromRect:NSMakeRect(panelRect.origin.x , source.size.height - panelRect.origin.y - panelRect.size.height, panelRect.size.width, panelRect.size.height)
             operation:NSCompositeCopy
              fraction:1.0];

    [NSGraphicsContext restoreGraphicsState];
    //end drawing
    [target unlockFocus];

    //create a NSBitmapImageRep
    NSBitmapImageRep *bmpImageRep = [[[NSBitmapImageRep alloc]initWithData:[target TIFFRepresentation]] autorelease];
    //add the NSBitmapImage to the representation list of the target
    [target addRepresentation:bmpImageRep];
    //get the data from the representation
    NSData *data = [bmpImageRep representationUsingType: NSJPEGFileType
                                             properties: imageProps];
    NSString *filename = [NSString stringWithFormat:@"%@%@.jpg", panelImagePrefix, panelNumber];
    NSLog(@"This is the filename: %@", filename);
    //write the data to a file
    [data writeToFile:filename atomically:NO];

这是原始图像和裁剪图像的放大比较:

The Original Image (原始图像 - 上图)

The Cropped Image (裁剪后的图像 - 上图)

差异很难看出,但如果你在它们之间滑动,你就会注意到它。您也可以使用颜色选择器来注意差异。例如,图像底行最暗的像素是不同的阴影。

我还有一个解决方案,它在 iOS 中完全按照我想要的方式工作。这是代码:

-(void)testMethod:(int)page forRect:(CGRect)rect{
    NSString *filePath = @"imageName";

    NSData *data = [HeavyResourceManager dataForPath:filePath];//this just gets the image as NSData
    UIImage *image = [UIImage imageWithData:data];

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);//crop in the rect

    UIImage *result = [UIImage imageWithCGImage:imageRef scale:0 orientation:image.imageOrientation];
    CGImageRelease(imageRef);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];

    [UIImageJPEGRepresentation(result, 1.0) writeToFile:[documentsDirectoryPath stringByAppendingPathComponent::@"output.jpg"] atomically:YES];
}

那么,有没有一种方法可以在 OSX 中裁剪图像,使裁剪后的图像完全不变?也许我必须查看不同的库,但如果我不能用 Objective-C 做到这一点,我会感到惊讶......


注意,这是我之前问题的后续问题 here .


更新 我已经尝试(根据 suggestion )将 CGRect 值四舍五入为整数,但没有注意到差异。这是我使用的代码:

    [source drawInRect:NSMakeRect(0,0,(int)panelRect.size.width,(int)panelRect.size.height)
              fromRect:NSMakeRect((int)panelRect.origin.x , (int)(source.size.height - panelRect.origin.y - panelRect.size.height), (int)panelRect.size.width, (int)panelRect.size.height)
             operation:NSCompositeCopy
              fraction:1.0];

更新 我试过了mazzaroth code如果我将它保存为 png,它会工作,但如果我尝试将它保存为 jpeg,图像质量会下降。如此接近,但还不够接近。仍然希望得到一个完整的答案...

最佳答案

使用 CGImageCreateWithImageInRect。

// this chunk of code loads a jpeg image into a cgimage
// creates a second crop of the original image with CGImageCreateWithImageInRect
// writes the new cropped image to the desktop
// ensure that the xy origin of the CGRectMake call is smaller than the width or height of the original image

NSURL *originalImage = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"lockwood" ofType:@"jpg"]];
CGImageRef imageRef = NULL;

CGImageSourceRef loadRef = CGImageSourceCreateWithURL((CFURLRef)originalImage, NULL);
if (loadRef != NULL)
{
    imageRef = CGImageSourceCreateImageAtIndex(loadRef, 0, NULL);
    CFRelease(loadRef); // Release CGImageSource reference
}    
CGImageRef croppedImage = CGImageCreateWithImageInRect(imageRef, CGRectMake(200., 200., 100., 100.));

CFURLRef saveUrl = (CFURLRef)[NSURL fileURLWithPath:[@"~/Desktop/lockwood-crop.jpg" stringByExpandingTildeInPath]];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(saveUrl, kUTTypeJPEG, 1, NULL);
CGImageDestinationAddImage(destination, croppedImage, nil);

if (!CGImageDestinationFinalize(destination)) {
    NSLog(@"Failed to write image to %@", saveUrl);
}

CFRelease(destination);
CFRelease(imageRef);
CFRelease(croppedImage);

我也做了一个要点:

https://gist.github.com/4259594

关于objective-c - 如何在 Objective-c/Cocoa (OSX) 中做出完美的裁剪(不改变质量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13716426/

相关文章:

macos - MonoMac Create Mac Installer 导致 Merging Mono Failed。致命的未处理异常

iphone - 在 IPHONE 中使用 Cocoa AES Rijndael 进行加密,需要使用 .NET 进行解密

macos - 在 OSX 中以最大化形式初始化 NSwindowcontroller

ios - 自定义 Xcode IDE 插件错误 : "Could not find class named..."

python - 当玩家死亡时退出游戏结束

cocoa - 从 cocoa 应用程序访问网络服务器

objective-c - 如何使用 Objective-C 将 mp3 歌曲导入 iTunes?

ios - 使用 splitViewController :willChangeToDisplayMode: in iOS8 时如何显示 barButtonItem

objective-c - 从 cocoa 应用程序内部运行 WPS

objective-c - Cocoa NSStatusItem 图像 – 不透明背景