扩展NSImage并保存

时间:2013-03-23 13:49:57

标签: objective-c macos nsimage nsimageview nsbitmapimagerep

我想扩大64px的图像以使其成为512px(即使它模糊或像素化)

我使用它来从我的NSImageView获取图像并保存它:

NSData *customimageData = [[customIcon image] TIFFRepresentation];
    NSBitmapImageRep *customimageRep = [NSBitmapImageRep imageRepWithData:customimageData];


    customimageData = [customimageRep representationUsingType:NSPNGFileType properties:nil];



    NSString* customBundlePath = [[NSBundle mainBundle] pathForResource:@"customIcon" ofType:@"png"];
    [customimageData writeToFile:customBundlePath atomically:YES];

我已经尝试过setSize:但它仍然保存了64px。

提前致谢!

1 个答案:

答案 0 :(得分:11)

您不能使用NSImage的size属性,因为它只与图像表示的像素尺寸有间接关系。调整像素尺寸大小的好方法是使用NSImageRepdrawInRect方法:

 - (BOOL)drawInRect:(NSRect)rect
  

在指定的矩形中绘制整个图像,根据需要缩放以适合。

这是一个图像大小调整方法(以你想要的像素大小创建一个新的NSImage)。

- (NSImage*) resizeImage:(NSImage*)sourceImage size:(NSSize)size
{

    NSRect targetFrame = NSMakeRect(0, 0, size.width, size.height);     
    NSImage* targetImage = nil;
    NSImageRep *sourceImageRep =
    [sourceImage bestRepresentationForRect:targetFrame
                                   context:nil
                                     hints:nil];

    targetImage = [[NSImage alloc] initWithSize:size];

    [targetImage lockFocus];
    [sourceImageRep drawInRect: targetFrame];
    [targetImage unlockFocus];

return targetImage; 
}

这是我在这里给出的更详细的答案:NSImage doesn't scale

另一个有效的调整大小方法是NSImage方法drawInRect:fromRect:operation:fraction:respectFlipped:hints

- (void)drawInRect:(NSRect)dstSpacePortionRect 
          fromRect:(NSRect)srcSpacePortionRect 
         operation:(NSCompositingOperation)op 
          fraction:(CGFloat)requestedAlpha 
    respectFlipped:(BOOL)respectContextIsFlipped 
             hints:(NSDictionary *)hints

此方法的主要优点是hints NSDictionary,您可以在其中控制插值。当放大图像时,这可以产生广泛不同的结果。 NSImageHintInterpolation是一个枚举,可以采用五个值中的一个......

    enum {
       NSImageInterpolationDefault = 0,
       NSImageInterpolationNone = 1,
       NSImageInterpolationLow = 2,
       NSImageInterpolationMedium = 4,
       NSImageInterpolationHigh = 3
    };
    typedef NSUInteger NSImageInterpolation;

使用这种方法不需要提取imageRep的中间步骤,NSImage会做正确的事......

- (NSImage*) resizeImage:(NSImage*)sourceImage size:(NSSize)size
{
    NSRect targetFrame = NSMakeRect(0, 0, size.width, size.height);
    NSImage*  targetImage = [[NSImage alloc] initWithSize:size];

    [targetImage lockFocus];

    [sourceImage drawInRect:targetFrame
                   fromRect:NSZeroRect       //portion of source image to draw 
                  operation:NSCompositeCopy  //compositing operation
                   fraction:1.0              //alpha (transparency) value
             respectFlipped:YES              //coordinate system
                      hints:@{NSImageHintInterpolation:
     [NSNumber numberWithInt:NSImageInterpolationLow]}];

    [targetImage unlockFocus];

    return targetImage;
}