Skip to content

Instantly share code, notes, and snippets.

@linktoming
Created October 31, 2012 10:00
Show Gist options
  • Save linktoming/3986189 to your computer and use it in GitHub Desktop.
Save linktoming/3986189 to your computer and use it in GitHub Desktop.
Crop and Scale CGContext - iOS
//Crop and Scale CGContext - iOS
//http://pastebin.com/8xWrr1tv
- (void)modifyImage:(CMSampleBufferRef) sampleBuffer {
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the image buffer
CVPixelBufferLockBaseAddress(imageBuffer,0);
// Get information about the image
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
// Create a CGImageRef from the CVImageBufferRef
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGContextSaveGState(context);
CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextFillRect(context, CGRectMake(0, 0, 400, 400));
//restore the context and remove the clipping area.
CGContextRestoreGState(context);
// We unlock the image buffer
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
// We release some components
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment