Skip navigation.
 
mlCropping an NSBitmapImageRep to a given NSRect?
FROM : Daniel Thorpe
DATE : Mon Apr 21 13:43:14 2008

Hello everyone,

I can't seem to get this to work, yet it seems like it should be so 
easy. I have an NSBitmapImageRep, and I want to crop it to a given 
NSRect. The code I've attempted so far is this:

   // Create an NSImage for the current image rep
   NSImage *source = [[NSImage alloc] init];
   
   // Add the image rep to the source
   [source addRepresentation:imageRep];    
   
   // Let's just write this to file
   [[source TIFFRepresentation] writeToFile:[NSString stringWithFormat:@"%@_source.tiff
", label] atomically:YES];
   
   self.extent = [imageRep nonZeroBounds];    // This is our NSRect, 
computed using a category method of NSBitmapImageRep
   
   NSImage *target = [[NSImage alloc] initWithSize:extent.size];    
       
   // Set the target as the current drawing context
   [target lockFocus];
   // Composite a rectange of the source to a point in the target
   [[NSGraphicsContext currentContext] setShouldAntialias:NO];
   [source compositeToPoint:NSZeroPoint fromRect:extent 
operation:NSCompositeSourceIn fraction:1.0];
   [target unlockFocus];

   // Let's just write this to file
   [[target TIFFRepresentation] writeToFile:[NSString stringWithFormat:@"%@_cropped.tiff
", label] atomically:YES];

I've not really used Quartz before, but this seems to be how all these 
methods work. Although it's not working, the cropped image is the 
right size, but is just black and doesn't contain the right rect of 
the source image... what am I doing wrong?

As always, the help from people on the list is really appreciated, 
thanks!

Cheers
Dan

Related mailsAuthorDate
mlCropping an NSBitmapImageRep to a given NSRect? Daniel Thorpe Apr 21, 13:43
mlRe: Cropping an NSBitmapImageRep to a given NSRect? Graham Cox Apr 21, 13:55
mlRe: Cropping an NSBitmapImageRep to a given NSRect? Graham Cox Apr 21, 13:57
mlRe: Cropping an NSBitmapImageRep to a given NSRect? Daniel Thorpe Apr 21, 14:23
mlRe: Cropping an NSBitmapImageRep to a given NSRect? Graham Cox Apr 21, 14:41
mlRe: Cropping an NSBitmapImageRep to a given NSRect? Daniel Thorpe Apr 21, 15:21
mlRe: Cropping an NSBitmapImageRep to a given NSRect? Graham Cox Apr 21, 15:41
mlRe: Cropping an NSBitmapImageRep to a given NSRect? [Solved] Daniel Thorpe Apr 21, 15:46