'''
@author: Scondo

Module for reading jpeg parameters like size, colorspace etc.
'''
import binascii

class JPGInfo(object):
    def readSOF(self,data,typ=1):
        SOFlen=ord(data[0])*256+ord(data[1])
        if typ<3:
            #precision of one plane
            self.precision=ord(data[2])
            #width then height as in PIL 
            self.size=(ord(data[5])*256+ord(data[6]),ord(data[3])*256+ord(data[4]))
            #number of planes
            self.nplanes=ord(data[7])
        return SOFlen
    
    def readJFIF(self,data):
        JFIFlen=ord(data[0])*256+ord(data[1])
        #2-6 - jfif marker, 7-8 - jfif version
        runit=ord(data[9])
        if runit==0:
            self.res_units="pt"
            return JFIFlen
        elif runit==1:
            self.res_units="in"
        elif runit==2:
            self.res_units="mm"
        else:
            return JFIFlen
        self.resolution=(ord(data[10])*256+ord(data[11]),ord(data[12])*256+ord(data[13]))
        return JFIFlen    
    def __init__(self,my_file):
        data=my_file.read()
        pos=0
        while True: 
            pos=data.find(chr(255),pos)
            if pos==-1:
                break;
            pos+=1
            marker=binascii.hexlify(data[pos])
            if marker[0]=="c" and marker[1]<>"4" and marker[1]<>"c":
                pos=pos+self.readSOF(data[pos+1:],int(marker[1],16))
            elif marker=="e0":
                pos=pos+self.readJFIF(data[pos+1:])    
        
if __name__=="__main__":
    info=JPGInfo(open("../logo_pb.jpg"))
    print info.precision
    print info.size
    print info.nplanes
    print info.res_units
    print info.resolution