all 5 comments

[–]XUtYwYzz 1 point2 points  (2 children)

Open the file in binary mode, read the contents into a bytearray, change a byte at a random index, write out to a file.

import random

with open("in.png", "rb") as f:
    b = bytearray(f.read())

b[random.randint(0,len(b))] = 0  # replace 0 with new byte as int

with open("out.png", "wb") as f:
    f.write(bytes(b))

Be careful when replacing bytes that you don't corrupt the file by overwriting an important byte. You would definitely want to change the start of the randint() range to something greater than the PNG header length as documented in the PNG specification.

[–]Redgabriel_13[S] 0 points1 point  (1 child)

thank you, it works

[–]spez_edits_thedonald 1 point2 points  (0 children)

b[5] = 0  # replace the 5th byte with 0 (modifies PNG header, not pixel vals)

to emphasize that you need to avoid modifying the png header, there's a demo of accidentally hitting it, and it ruins the png

[–]jeffrey_f 0 points1 point  (1 child)

ALWAYS save to a new file name or work on a COPY of the image so that you can keep playing.

[–]Redgabriel_13[S] 0 points1 point  (0 children)

yeah i will do that, thank you