Code Snippets
The latest snippet
Image overlay with NSImage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // Set our height and width (using ebonics)
float wiff = 10.0;
float heiff = 10.0;
// Create a new image for us that will will draw the other images on to.
NSImage *finalImage = [[NSImage alloc] initWithSize:NSMakeSize(wiff, heiff)];
// Grab our overlay and mainImage from our file system.
NSImage *overlay = [[NSImage alloc] initWithData:[NSData dataWithContentsOfFile:@"/path/to/overlay_image.jpg"]];
NSImage *mainImage = [[NSImage alloc] initWithData:[NSData dataWithContentsOfFile:@"/path/to/main_image.jpg"]];
// Lock focus, this way we can manipulate the image we are focused on
[finalImage lockFocus];
// First we draw our mainImage on the image we created
[mainImage drawInRect:NSMakeRect(0, 0, wiff, heiff)
fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
// Now let's draw our overlay image on top of our mainImage with a bottom/left offset of 10
[overlay drawInRect:NSMakeRect(10, 10, [overlay size].width, [overlay size].height)
fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
// Finished drawing, let's unlock focus.
[finalImage unlockFocus];
// Create a data object from the image we created.
NSData *finalData = [finalImage TIFFRepresentation];
// Now we write our image to file and then we can go
// to the track and place a cool G on the horse "Cocoa gives him runs"
[[[NSBitmapImageRep imageRepWithData:finalData]
representationUsingType:NSJPEGFileType properties:nil]
writeToFile:[NSString stringWithFormat:@"/path/to/folder/new_image.jpg"] atomically:YES];
|

RSS Feed