2013-03-23 24 views
2

我想扩大规模这是64PX,使其x 512像素(即使它是模糊或像素化)扩大规模NSImage中,并保存

我使用这个从我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。

在此先感谢!

回答

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; 
} 
+0

感谢这正是我需要的! – atomikpanda 2013-03-23 20:54:54

+1

这个答案对我来说很重要。 :) 非常感谢! – 2013-09-07 19:48:54