2

I'm working on a program that uses a BMP and a separate file for the transparency layer. I need to convert them into a PNG from that so I'm using PIL in python to do so. However, I need the data from the transparency file in hex so it can be added to the image. I am using the binascii.hexlify function to do that.

Now, the problem I'm having is for some reason the data, after going through the hexlify function (I've systematically narrowed it down by going through my code piece by piece), looks different than it does in my hex editor and is causing slight distortions in the images. I can't seem to figure out where I am going wrong.

Data before processing in Hex editor

Data after processing in Hex editor

Here is the problematic part off my code:

filename = askopenfilename(parent=root)
with open(filename, 'rb') as f:
    content = f.read()
    f.close()
hexContent = binascii.hexlify(content).decode("utf-8")

My input

My output (This is hexcontent written to a file. Since I know that it is not going wrong in the writing of the file, and it is also irrelevant to my actual program I did not add that part to the code snippet)

Before anyone asks I tried codecs.encode(content, 'hex') and binascii.b2a_hex(content).

As for how I know that it is this part that is messing up, I printed out binascii.hexlify(content) and found the same part as in the hex editor and it looked identical to what I had got in the end.

Another possibility for where it is going wrong is in the "open(filename, 'rb')" step. I haven't yet thought of a way to test that. So any help or suggestions would be appreciated. If you need one of the files I'm using for testing purposes, I'll gladly add one here.

Yascob
  • 21
  • 2

1 Answers1

0

If I understand your question correctly then your desired output should match Data before processing in Hex editor. I can obtain this with the following code:

with open('Input.alp', 'rb') as f:
    i = 0
    for i, chunk in enumerate(iter(lambda: f.read(16), b'')):
        if 688 <= i * 16 <= 736:
            print i * 16, chunk.encode('hex')

Outputs:

688 ffffffffffffffffffffffffffffffff
704 ffffffffffffffffffffffe000000000
720 000000000000000001dfffffffffffff
736 ffffffffffffffffffffffffffffffff

See this answer for a more detailed explanation.

Community
  • 1
  • 1
FujiApple
  • 796
  • 5
  • 16
  • Yup, you understood correctly. Sorry for writing it in a confusing manner. I'll try that method and see if it solves my problem. – Yascob Aug 21 '16 at 20:56