1

My question is related to this link

I would like to know how we can save images larger than device resolution using CGBitmapContextCreate .

Any sample code for guidance will be much appreciated.

thanks!

Community
  • 1
  • 1
Rohan
  • 2,939
  • 5
  • 36
  • 65

1 Answers1

4

Don't use CGBitmapContextCreate, use UIGraphicsBeginImageContextWithOptions, it's much easier. Use it like this:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 1.0f);
CGContextRef context = UIGraphicsGetCurrentContext();

//do your drawing

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEdnImageContext();

//your resultant UIImage is now stored in image variable

The three parameters to UIGraphicsBeginImageContext are:

  1. The size of the image - this can be anything you want

  2. Whether the image has transparency or not

  3. The scale of pixels in the image. 0.0 is the default, so on an iPhone 3GS it will be 1.0 and on an iPhone 4 with a retina display it will be 2.0. You can pass in any scale you want though, so if you pass in 5.0, each pixel unit in your image will actually be 5x5 pixels in the bitmap, just like 1 pixel on a Retina display is really 2x2 pixels on screen.

Edit: it turns out that the question of whether UIGraphicsBeginImageContext() is thread-safe seems to be a bit controversial. If you do need to do this concurrently on a background thread, there is an alternative (rather more complex approach) using CGBitMapContextCreate() here: UIGraphicsBeginImageContext vs CGBitmapContextCreate

Community
  • 1
  • 1
Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103
  • 1
    It is not good solution. UIGraphicsBeginImageContext and other UI... functions are not thread safe, they are running on the main tread. When you use this function, UI of your application will freeze. – Martin Pilch Feb 03 '12 at 14:17
  • Who said anything about threads? Anyway, if you need to use it in a threaded context, you could always wrap the UIGraphicsBeginImageContext() in a @synchronized block and do your actual drawing once you've got the CGContextRef. – Nick Lockwood Feb 03 '12 at 14:20
  • @MartinPilch The fact that they all run on the main thread is what makes them thread safe. They are only called from a single thread - **the main thread** so threading doesn't come into it. – Abizern Feb 03 '12 at 15:40
  • thaks for replay. i have used the same code but problem is that when i save larger resolution image , it saves the image with the device's resolution. and i want to save the image with it's original resolution. And UIGraphicsBeginImageContext(CGSizeMake(width, height), YES, 0.0f); gives the error " of too many arguments".. – Rohan Feb 04 '12 at 06:57
  • 1
    Sorry, should have been UIGraphicsBeginImageContextWithOptions - I've updated the answer. – Nick Lockwood Feb 04 '12 at 09:34