HomoVafer
HomoVafer

Reputation: 333

Modify images by bytes with python

I'm developing a program that will apply some effects to images. To do that I'd like to use bytes and here I have a problem.

I need to chose an image file and get a list of INTEGER conteining the bytes and then modify this list and then save the new file using my new list.

I have this code but in this way I can't set an integer value:

in_file = open(input('Input image: '), "rb")
data = in_file.read()
in_file.close()

for num in range(0, len(data), 4):
    b = int(data[num])
    print(b)
    g = int(data[num + 1])
    r = int(data[num + 2])
    a = int(data[num + 3])
    media = (b + g + r) / 3
    data[num] = media
    data[num + 1] = media
    data[num + 2] = media

out_file = open(input('Output image: '), "wb")
out_file.write(data)
out_file.close()

I don't know if this code is correct and it can do what I want, if this code have an error please correct it, if this code is totally wrong can you give me another way to do that?

Thanks

Upvotes: 1

Views: 832

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

In Python 3, when you read a binary file, you get a bytes object, which is like a list of integer values (0-255) but immutable.

Start by doing:

data = list(in_file.read())

now you have a list of integers you can modify in your following loop.

Once you changed the values, just convert back to bytes when writing:

out_file.write(bytes(data))

Upvotes: 1

Related Questions