1

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

1
  • Sounds hard. Maybe you should use Pillow instead of manual bit flipping. Commented Sep 15, 2017 at 15:22

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.