0

I'm taking a "snapshot" of the image context in UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, true, 0) and eventually creating a UIImage using

var renderedImage = UIGraphicsGetImageFromCurrentImageContext()

However I need to get the NSData representation of this UIImage without using UIImageJPEGRepresentation or UIImagePNGRepresentation (because these produce files that are way larger than the original UIImage). How can I do this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • What image representation should the NSData contain? – rmaddy May 22 '15 at 19:44
  • FYI, you can reduce the size of the image by adding in another parameter `UIImageJPEGRepresentation(yourImage, 0.9f)` – Josh Gafni May 22 '15 at 19:44
  • @rmaddy it should be in jpeg. I don't want to reduce the quality though. If I save the exact same image to the Photos Album using `ALAssetsLibrary` the image size is almost 4 times smaller, but no compression seems to have occurred. – Tometoyou May 22 '15 at 19:47
  • It must be compressing it if it's four times smaller. – rmaddy May 22 '15 at 19:49

2 Answers2

0

I'm not sure what you mean by "way larger" than the original UIImage. The data backing the UIImage object is at least as big as the data you would get by converting it into a JPG, and roughly equivalent to the data you would get by converting it to a PNG.

The rendered image will be twice the screen size in points, because you have rendered a retina screen into an image.

You can avoid this and render the image as non-retina by making your image context have a scale of 1:

UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, true, 1)
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
bdrell
  • 194
  • 2
  • 5
0

these produce files that are way larger than the original UIImage). How can I do this?

Image files contain compressed data, while NSData is raw i.e. not compressed. Therefore NSData will in about all cases be larger, when written into a file.

More info at another question: convert UIImage to NSData

Community
  • 1
  • 1
JOM
  • 8,139
  • 6
  • 78
  • 111