Howto Extract PNG from binary file @ 0x80?

Aaron mishpaha at telus.net
Wed Dec 22 23:23:51 EST 2004


On Sat, 11 Dec 2004 10:53:19 +0100, Fredrik Lundh wrote:

> "flamesrock" <mishpaha at telus.net> wrote:
> 
>> As a newbie to the language, I have no idea where to start..please bare
>> with me..
>>
>> The simcity 4 savegame file has a png image stored at the hex location
>> 0x80. What I want to extract it and create a file with the .png
>> extension in that directory.
>>
>> Can somebody explain with a snippet of code how I would accomplish
>> this? I've looked around but the information is too vague and I don't
>> know how to start.
> 
> there are *many* ways to ignore the first 128 bytes when you read a file
> (you can seek to the right location, you can read 128 bytes and throw them
> a way, you can read one byte 128 times and throw each one of them away,
> you can read all data and remove the first 128 bytes, etc).
> 
> here's a snippet that understands the structure of the PNG, and stops copying
> when it reaches the end of the PNG:
> 
> import struct
> 
> def pngcopy(infile, outfile):
> 
>     # copy header
>     header = infile.read(8)
>     if header != "\211PNG\r\n\032\n":
>         raise IOError("not a valid PNG file")
>     outfile.write(header)
> 
>     # copy chunks, until IEND
>     while 1:
>         chunk = infile.read(8)
>         size, cid = struct.unpack("!l4s", chunk)
>         outfile.write(chunk)
>         outfile.write(infile.read(size))
>         outfile.write(infile.read(4)) # checksum
>         if cid == "IEND":
>             break
> 
> to use this, open the input file (the simcity file) and the output file
> (the png file you want to create) in binary mode, use the "seek"
> method to move to the right place in the simcity file, and call "pngcopy"
> with the two file objects.
> 
>     infile = open("mysimcityfile", "rb")
>     infile.seek(0x80)
>     outfile = open("myimage.png", "wb")
>     pngcopy(infile, outfile)
>     outfile.close()
>     infile.close()
> 
> hope this helps!
> 
> </F>

Thanks! And what a pleasant surprise! I just noticed you authored the book
I've been studying - Python Standard Library. Its awesome ;)

Oh- and Sorry for the late response. Google groups wouldn't allow me to
followup. I'm using pan now.




More information about the Python-list mailing list