0

I have the following objective-C function meant to resize an NSBitmapImageRep to a designated size.

Currently, when working with an image of size 2048x1536 and trying to resize it to 300x225, this function keeps returning an NSBitmapImageRep of size 600x450.

- (NSBitmapImageRep*) resizeImageRep: (NSBitmapImageRep*) anOriginalImageRep toTargetSize: (NSSize) aTargetSize
{
    NSImage* theTempImageRep = [[[NSImage alloc] initWithSize: aTargetSize ] autorelease];
    [ theTempImageRep lockFocus ];
    [NSGraphicsContext currentContext].imageInterpolation = NSImageInterpolationHigh;
    NSRect theTargetRect = NSMakeRect(0.0, 0.0, aTargetSize.width, aTargetSize.height);
    [ anOriginalImageRep drawInRect: theTargetRect];
    NSBitmapImageRep* theResizedImageRep = [[[NSBitmapImageRep alloc] initWithFocusedViewRect: theTargetRect ] autorelease];
    [ theTempImageRep unlockFocus];

    return theResizedImageRep;
}

Debugging it, I'm finding that theTargetRect is of the proper size, but the call to initWithFocusedRec returns a bitmap of 600x450 pixels (high x wide)

I'm at a complete loss as to why this may be happening. Does anyone have any insight?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
mosquito242
  • 353
  • 5
  • 17

1 Answers1

1

Your technique won't produce a resized image. For one thing, the method initWithFocusedViewRect:reads bitmap data from the focused window and is used to create screen grabs.

You should create a new graphics context with a new NSBitmapImageRep or NSImage of the desired size then you draw your image into that context.

Something like this.

NSGraphicsContext* context = [NSGraphicsContext graphicsContextWithBitmapImageRep:theTempImageRep];

if (context)
{
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:context];

    [anOriginalImageRep drawAtPoint:NSZeroPoint];
    [anOriginalImageRep drawInRect:theTargetRect];

    [NSGraphicsContext restoreGraphicsState];
}
// Now your temp image rep should have the resized original.
Jason
  • 1,612
  • 16
  • 23
  • Are you sure? I'm inheriting an old codebase (currently on the 10.7SDK and updating it) so the code they have should be functional, unless there were API changes. I assumed it was just a change in the way the new objective C handles bitmap pixel resolution. – mosquito242 Jan 06 '16 at 22:30
  • That code is from a working project. I don't think there's anything in there which wouldn't work on 10.7, but it certainly works on 10.9+ – Jason Jan 07 '16 at 01:19