Convert NSImage to CVPixelBufferRef


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  1. - (CVPixelBufferRef)fastImageFromNSImage:(NSImage *)image
  2. {
  3. CVPixelBufferRef buffer = NULL;
  4.  
  5.  
  6. // config
  7. size_t width = [image size].width;
  8. size_t height = [image size].height;
  9. size_t bitsPerComponent = 8; // *not* CGImageGetBitsPerComponent(image);
  10. CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
  11. CGBitmapInfo bi = kCGImageAlphaNoneSkipFirst; // *not* CGImageGetBitmapInfo(image);
  12. NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey, [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey, nil];
  13.  
  14. // create pixel buffer
  15. CVPixelBufferCreate(kCFAllocatorDefault, width, height, k32ARGBPixelFormat, (CFDictionaryRef)d, &buffer);
  16. CVPixelBufferLockBaseAddress(buffer, 0);
  17. void *rasterData = CVPixelBufferGetBaseAddress(buffer);
  18. size_t bytesPerRow = CVPixelBufferGetBytesPerRow(buffer);
  19.  
  20. // context to draw in, set to pixel buffer's address
  21. CGContextRef ctxt = CGBitmapContextCreate(rasterData, width, height, bitsPerComponent, bytesPerRow, cs, bi);
  22. if(ctxt == NULL){
  23. NSLog(@"could not create context");
  24. return NULL;
  25. }
  26.  
  27. // draw
  28. NSGraphicsContext *nsctxt = [NSGraphicsContext graphicsContextWithGraphicsPort:ctxt flipped:NO];
  29. [NSGraphicsContext saveGraphicsState];
  30. [NSGraphicsContext setCurrentContext:nsctxt];
  31. [image compositeToPoint:NSMakePoint(0.0, 0.0) operation:NSCompositeCopy];
  32. [NSGraphicsContext restoreGraphicsState];
  33.  
  34. CVPixelBufferUnlockBaseAddress(buffer, 0);
  35. CFRelease(ctxt);
  36.  
  37. return buffer;
  38. }

URL: http://lists.apple.com/archives/quartz-dev/2006/Oct/msg00096.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.