调整大小并保存NSImage?

时间:2011-03-10 19:43:30

标签: objective-c macos nsimage nsimageview nsopenpanel

我有一个NSImageView,我从NSOpenPanel获取图像。这很有效。

现在,我怎样才能将NSImage的大小减半,并将其保存为与原始目录相同的格式?

如果您可以随心所欲地提供帮助,谢谢。

7 个答案:

答案 0 :(得分:7)

检查Matt Gemmell的ImageCrop示例项目:
http://mattgemmell.com/source/

如何调整大小/裁剪图像的好例子 最后你可以使用这样的东西来保存结果(脏样本):

// Write to TIF
[[resultImg TIFFRepresentation] writeToFile:@"/Users/Anne/Desktop/Result.tif" atomically:YES];

// Write to JPG
NSData *imageData = [resultImg  TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] forKey:NSImageCompressionFactor];
imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
[imageData writeToFile:@"/Users/Anne/Desktop/Result.jpg" atomically:NO];

答案 1 :(得分:4)

由于NSImage对象是不可变的,因此您必须:

  1. 创建一个与新图像大小相当的核心图形上下文。
  2. 将NSImage绘制到CGContext中。它应该自动为你缩放。
  3. 从该上下文创建NSImage
  4. 写出新的NSImage
  5. 不要忘记释放您分配的任何临时对象。
  6. 肯定还有其他选择,但这是第一个想到的选择。

答案 2 :(得分:3)

+(NSImage*) resize:(NSImage*)aImage scale:(CGFloat)aScale
{
    NSImageView* kView = [[NSImageView alloc] initWithFrame:NSMakeRect(0, 0, aImage.size.width * aScale, aImage.size.height* aScale)];
    [kView setImageScaling:NSImageScaleProportionallyUpOrDown];
    [kView setImage:aImage];

    NSRect kRect = kView.frame;
    NSBitmapImageRep* kRep = [kView bitmapImageRepForCachingDisplayInRect:kRect];
    [kView cacheDisplayInRect:kRect toBitmapImageRep:kRep];

    NSData* kData = [kRep representationUsingType:NSJPEGFileType properties:nil];
    return [[NSImage alloc] initWithData:kData];
}

答案 3 :(得分:2)

这是一个具体的实现

-(NSImage*)resizeImage:(NSImage*)input by:(CGFloat)factor
{    
    NSSize size = NSZeroSize;      
    size.width = input.size.width*factor;
    size.height = input.size.height*factor; 

    NSImage *ret = [[NSImage alloc] initWithSize:size];
    [ret lockFocus];
    NSAffineTransform *transform = [NSAffineTransform transform];
    [transform scaleBy:factor];  
    [transform concat]; 
    [input drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];    
    [ret unlockFocus];        

    return [ret autorelease];
}

请记住,这是基于像素的,HiDPI必须考虑缩放,很容易获得:

-(CGFloat)pixelScaling
{
    NSRect pixelBounds = [self convertRectToBacking:self.bounds];
    return pixelBounds.size.width/self.bounds.size.width;
}

答案 4 :(得分:0)

答案 5 :(得分:0)

这里有一些代码比其他答案更广泛地使用Core Graphics。它是根据Mark Thalman's answer中对此问题的提示而制作的。

此代码根据目标图像宽度缩小NSImage。这有点令人讨厌,但仍可用作记录如何在NSImage中绘制CGContext的额外示例,以及如何将CGBitmapContextCGImage的内容写入文件

您可能需要添加额外的错误检查。我的用例并不需要它。

- (void)generateThumbnailForImage:(NSImage*)image atPath:(NSString*)newFilePath forWidth:(int)width
{
    CGSize size = CGSizeMake(width, image.size.height * (float)width / (float)image.size.width);
    CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();

    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width * 4, rgbColorspace, bitmapInfo);
    NSGraphicsContext * graphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
    [NSGraphicsContext setCurrentContext:graphicsContext];

    [image drawInRect:NSMakeRect(0, 0, size.width, size.height) fromRect:NSMakeRect(0, 0, image.size.width, image.size.height) operation:NSCompositeCopy fraction:1.0];

    CGImageRef outImage = CGBitmapContextCreateImage(context);
    CFURLRef outURL = (CFURLRef)[NSURL fileURLWithPath:newFilePath];
    CGImageDestinationRef outDestination = CGImageDestinationCreateWithURL(outURL, kUTTypeJPEG, 1, NULL);
    CGImageDestinationAddImage(outDestination, outImage, NULL);
    if(!CGImageDestinationFinalize(outDestination))
    {
        NSLog(@"Failed to write image to %@", newFilePath);
    }
    CFRelease(outDestination);
    CGImageRelease(outImage);
    CGContextRelease(context);
    CGColorSpaceRelease(rgbColorspace);
}

答案 6 :(得分:0)

调整图片大小

- (NSImage *)scaleImage:(NSImage *)anImage newSize:(NSSize)newSize
{
    NSImage *sourceImage = anImage;
    if ([sourceImage isValid])
    {
        if (anImage.size.width == newSize.width && anImage.size.height == newSize.height && newSize.width <= 0 && newSize.height <= 0) {
            return anImage;
        }

        NSRect oldRect = NSMakeRect(0.0, 0.0, anImage.size.width, anImage.size.height);
        NSRect newRect = NSMakeRect(0,0,newSize.width,newSize.height);
        NSImage *newImage = [[NSImage alloc] initWithSize:newSize];

        [newImage lockFocus];
        [sourceImage drawInRect:newRect fromRect:oldRect operation:NSCompositeCopy fraction:1.0];
        [newImage unlockFocus];

        return newImage;
    }
}