2

In an iPhone app I load a JPG image off a server using a standard HTTP request. The data comes back as NSData, which I can convert into a UIImage using the [UIImage imageWithData:responseData] function. My question is, can I convert the UIImage representation of my image back to the same NSData that it originated from? I know about the UIImageJPEGRepresentation() function, but I tried that with a compressionQuality of 1 and that gave me something different than the original NSData.

chris
  • 16,324
  • 9
  • 37
  • 40

2 Answers2

3

I think (guess, actually) your issue is probably because a UIImage is not stored in JPEG format internally. Because of the way JPEG compression works, it is unlikely that the conversion back to JPEG could give you the exact same data. Is there any reason why you can't keep the original NSData hanging around?

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • I guess the problem is analogous to repetitively opening and saving a JPG with PhotoShop. The lossy compression compounds and you never have the same image. The reason for not wanting to hold onto the NSData is for performance with CoreData (storing it as a BLOB). However, I just came across http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreData/Articles/cdPerformance.html, which outlined a solution to my problem. Thanks for your input. – chris Jun 27 '11 at 20:45
2

You should use UIImagePNGRepresentation(), and send files as PNGs to the device as well. PNG is much more efficient to load and save on the device. This is the standard method of converting an array of bytes (NSData) to/from an image.

If you're stuck with JPEG data, UIImageJPEGRepresentation() is the correct way to get it back to an NSData object. It might not be identical, depending on how Apple implemented that method it could update some of the data while technically still being the same image (would render the same).

Community
  • 1
  • 1
RyanR
  • 7,728
  • 1
  • 25
  • 39
  • I agree.. but unfortunately my source on the web server is a JPEG, and I'd like to convert the UIImage back to the same NSData representation of what was originally downloaded. – chris Jun 27 '11 at 16:52
  • I believe you're right that the created JPEG isn't identical, but this is the problem. I worry about compounding the lossy compression. I think the only solution is to store the NSData, which I'm now doing. Thanks for the response. – chris Jun 28 '11 at 06:26