我想把一张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。
提前感谢!
你不能使用NSImage的size
属性,因为它与图像表示的像素尺寸只有间接关系。调整像素尺寸的一个好方法是使用NSImageRep:
drawInRect
方法。 - (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不缩放
另一个有效的方法是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,可以接受以下五个值之一:
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;
}