Search code examples
pythonpng

Python: .png image file that wont open because of text before file signature


I have a large series of png files that have had some text added before the ‰PNG file signature. I'm trying to find a way of opening the files in python and deleting the extra text before writing to a new file, so I can view the images.

A screenshot from Notepad++ of the file can be seen in the below image to give a better understanding of the problem.

first few lines of file showing additional text before file signature

So far I have tried this code

infile = open('radar0.1.107652907', encoding='ANSI')
outfile = open('test.png', 'w', encoding='ANSI')

imagetext = infile.read()

pos = imagetext.find('‰')

outtext = imagetext[pos:]

outfile.write(imagetext)

But when I try and open the new file it wont open.

Any help would be massively appreciated


Solution

  • I was able to solve the issue using @BoarGules suggestion to work in binary. Code is below

    infile = open('radar0.1.107652907', 'rb')
    outfile = open('test.png', 'wb')
    
    imagetext = infile.read()
    
    pos = imagetext.find(b'\x89PNG')
    
    outtext = imagetext[pos:]
    
    outfile.write(outtext)
    
    
    infile.close()
    outfile.close()