14

I have a CGContextRef and I did my drawing stuff with the bitmap context.

Now, I would like to have a function call to get a UIImage for the CGContextRef. How do I do that?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
samwize
  • 25,675
  • 15
  • 141
  • 186

2 Answers2

32

Something like this :

-(UIImage*)doImageOperation
{
  // Do your stuff here
  CGImageRef imgRef = CGBitmapContextCreateImage(context);
  UIImage* img = [UIImage imageWithCGImage:imgRef];
  CGImageRelease(imgRef);
  CGContextRelease(context);
  return img;
}
Nyx0uf
  • 4,609
  • 1
  • 25
  • 26
  • Thanks! With that, I created a convenient method `UIImage* UIGraphicsGetImageFromImageContext (CGContextRef context)` to use. – samwize May 03 '11 at 08:09
  • 3
    This will only work if `context` is a CGBitmapContext; it probably will not work on any other kind of CGContext. @samwize: You should name it something different. Prefixes are namespaces-by-convention; Apple may add a function named `UIGraphicsGetImageFromImageContext`, public or private, at any time, and if they do, yours will cause problems. Use your own prefix. – Peter Hosey May 03 '11 at 14:32
  • Hello @NyxOuf, I want to get the image out CgContextref, and pass that image to different ViewController. is that possible? and how can we do it.can we directly pass this image to any viewController and display it there?. waiting for your reply. – Ranjit Jul 18 '12 at 11:32
  • I don't understand. Just add a property to your VC and that's all.. @property (strong) UIImage* img; – Nyx0uf Jul 19 '12 at 07:50
9

Updated for Swift 3, this is a convenience function that takes a CGContext and returns a UIImage. Note that you no longer need to free the context when you're done with it in Swift 3.

func imageFromContext(_ context: CGContext) -> UIImage? {
    guard let cgImage = context.makeImage() else { return nil }
    return UIImage.init(cgImage: cgImage)
}
Echelon
  • 7,306
  • 1
  • 36
  • 34
  • Yeah, this was what I always used to use. Tried it today and bam: the images come out upside down. – Ash Feb 12 '21 at 16:25