objective-cimagecocoansbitmapimagerep

Resized image not drawn correctly to bitmap


I wrote this method to resize an image and save it to a file:

- (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];
}

This way the image should be drawn inside the bitmap, which is resized, scaling it to fit. If I use this method to resize and save an image, I get a file with the correct size, but it's an empty image. What is wrong with this code?


Solution

  • - (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];
    }