0
>>> m1.putpixel((0,0),(1,2,3))
>>> asarray(m1)[0]
array([[  1,   2,   3],
       [  1,   0, 252],
       [  1,   0, 252],
       ...,
       [253,   0,   0],
       [253,   0,   0],
       [253,   0,   0]], dtype=uint8)
>>> m1.save('enc_png.jpg',"JPEG")
>>> m1 = Image.open('enc_png.jpg')
>>> asarray(m1)[0]
array([[  0,   0, 211],
       [  0,   0, 219],
       [  1,   4, 231],
       ...,
       [253,   0,   0],
       [253,   0,   0],
       [253,   0,   0]], dtype=uint8)

When I save the image into jpg the pixels change from (1,2,3) to (0,0,211). It works fine when I save it as png. How could I solve this issue?

3xpl017
  • 37
  • 5

1 Answers1

1

JPEG is a lossy compression format, but PNG is lossless.

When you saved your data as JPEG, it got compressed with data loss - this improves the size of the file and doesn't affect the quality of the image very much (if you crank the compression level up, the quality will deteriorate). "Data loss" means that some part of your data was irrecoverably substituted by some other data that made the compression ratio better. And what was written to the file doesn't have enough information (deliberately!) to restore every single byte of the original. So on decompression your bytes - alongside with their neighbours, BTW - got replaced by something else.

PNGs compress data in such a way that they can be fully restored during decompression, so all your bytes remained the same.

ForceBru
  • 43,482
  • 10
  • 63
  • 98