0

Why does this transformation fails to result in the same image data?

    let path = Bundle(for: type(of: self)).url(forResource: "Image", withExtension: "jpg")
    inputData = try! Data(contentsOf: path!)

    let testImage = UIImage(data: inputData)
    let testImageData = UIImageJPEGRepresentation(testImage!, 1.0)

    expect(testImageData).to(equal(inputData))

From what I understand UIImageJPEGRepresentation and UIImagePNGRepresentation can strip the image of meta data. Is that the reason?

Zsolt
  • 3,648
  • 3
  • 32
  • 47
  • I think that the problem not in `UIImageJPEGRepresentation` function but with `UIImage` construction. It is hard to reason about a content of `UIImage` internals one thing to mention that it most likely to unpack jpeg to some bitmap format. So, converting this back to jpeg doesn't guarantee to have same data. Btw, what you'd like to test with this code? – Ilia Nov 23 '18 at 12:06
  • thanks @ilya. this is just an excerpt from my test target simplified, but in general I am trying to see if I get back the same image I saved at some point. – Zsolt Nov 23 '18 at 12:11
  • 1
    In addition source file can have a lot of different features like interlacing etc. This kind of information most likely removed when creating `UIImage` object. In general there is no guarantee of having the same data with such chain of conversions. – Ilia Nov 23 '18 at 12:12
  • for your task you need to find another way to identify image objects, like some naming convention (use UUID as a file name) or more complex data structures. Moreover, comparing binary data objects might be not so performant as you need. – Ilia Nov 23 '18 at 12:16

2 Answers2

0

There is no particular reason why two JPEG files showing the same image would be identical. JPEG files have lots of header info, different compression algorithms, etc. And even if both files have a compression level of 1 (do they?) they are both lossy, so something will differ every time you expand and recompress. Your expectations here are just wrong. But then it also sounds like you’re trying to test something that does not need testing in the first place.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

I was facing the same Issue, and was able to solve using UIImagePNGRepresentation to convert the UIImage to Data, and then compared to see if both Data were equal.

Hilton Pintor
  • 300
  • 2
  • 8