调整后的图像未正确绘制到位图

时间:2014-01-20 13:30:08

标签: objective-c image cocoa nsbitmapimagerep

我写了这个方法来调整图像大小并将其保存到文件中:

- (BOOL) saveImage: (NSImage*) image withSize: (NSSize) size type: (NSBitmapImageFileType) type toURL: (NSURL*) URL {
    NSImage* outputImage= [[NSImage alloc]initWithSize: size];
    NSBitmapImageRep* bitmap= [[NSBitmapImageRep alloc]initWithBitmapDataPlanes: NULL pixelsWide: size.width pixelsHigh: size.height bitsPerSample:8 samplesPerPixel:4 hasAlpha: type==NSPNGFileType isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
    [outputImage addRepresentation: bitmap];
    [image lockFocusOnRepresentation: bitmap];
    [image drawInRect: NSMakeRect(0, 0, size.width, size.height) fromRect: NSZeroRect operation: NSCompositeCopy fraction: 1.0];
    [image unlockFocus];
    NSDictionary* properties= type==NSJPEGFileType? @{NSImageCompressionFactor : @1.0} : @{};
    NSData* outputData= [bitmap representationUsingType: type properties: properties];
    return [outputData writeToURL: URL atomically: YES];
}

这样,图像应该在位图内绘制,位图会调整大小,缩放以适应。如果我使用此方法调整大小并保存图像,我会得到一个大小正确的文件,但它是一个空图像。这段代码有什么问题?

1 个答案:

答案 0 :(得分:1)

- (BOOL) saveImage:(NSImage*)image
          withSize:(NSSize) size
              type:(NSBitmapImageFileType) type
             toURL:(NSURL*) URL
{
    NSImage *smallImage = [[NSImage alloc] initWithSize:size];
    [smallImage lockFocus];
    [image setSize:size];
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
    [image drawAtPoint:NSZeroPoint fromRect:CGRectMake(0, 0, size.width, size.height) operation:NSCompositeCopy fraction:1.0];
    [smallImage unlockFocus];

    NSData *outputData= [smallImage TIFFRepresentation];
    NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:outputData];
    NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] forKey:NSImageCompressionFactor];
    outputData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
    return [outputData writeToURL:URL atomically:YES];
}