我编写了这个方法来调整图像大小并将其保存到文件中:
- (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];
}
这样,图像应该在位图内绘制,调整大小,缩放以适应。如果我使用这种方法来调整和保存图像的大小,我会得到一个大小正确的文件,但它是一个空图像。这段代码有什么问题?