2013-03-23 51 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