from __future__ import print_function import os import glob import g from struct import * def readIMG(path): f = open(path, 'rb') dir = {} head, n = unpack('4sI', f.read(8)) for i in range(n): offset, size, _, name = unpack('IHH24s', f.read(32)) name = name.decode('latin') pos = name.index('\x00') if pos > 0: name = name[:pos] dir[name.lower()] = {'offset': offset, 'size': size, 'path': path, 'name': name} f.close() return dir def hasfile(dir, name): return name.lower() in dir def openFile(dir, name): if name.lower() in dir: entry = dir[name.lower()] f = open(entry['path'], 'rb') f.seek(entry['offset']*2048, 0) return f return None def extract1(dir, name, outname): if name.lower() in dir: entry = dir[name.lower()] infile = openFile(dir, name) outfile = g.opencreate(outname, 'wb') outfile.write(infile.read(entry['size']*2048)) outfile.close() infile.close() def extract(dir, path): i = 1; for name, entry in dir.items(): print(i, "extracting", entry['name']) infile = openFile(dir, name) outfile = g.opencreate(g.jp(path, entry['name']), 'wb') outfile.write(infile.read(entry['size']*2048)) outfile.close() infile.close() i+=1 def build(directory, name): img = g.opencreate(name, 'wb') cwd = os.getcwd() os.chdir(directory) files = glob.glob('*') img.write(pack('4sI', b"VER2", len(files))) tablepos = img.tell() img.seek(32*len(files), 1) curpos = (img.tell()+2047)//2048 img.seek(curpos*2048, 0) dir = [] for fname in files: f = open(fname, 'rb') data = f.read() f.close() img.write(data) size = (len(data)+2047)//2048 dir.append((curpos, size, fname)) curpos += size img.seek(curpos*2048, 0) img.seek(tablepos, 0) for entry in dir: img.write(pack('IHH24s', entry[0], entry[1], 0, entry[2].encode())) img.close() os.chdir(cwd)