Data to UIImage to UIImageJPEGRepresentation equality failure

142 views Asked by At

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?

2

There are 2 answers

0
matt On

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.

1
Hilton Pintor On

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.