Discuss / Python / 交作业——struct判断位图

交作业——struct判断位图

Topic source

安迪博德

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
#检查任意文件是否是位图文件,如果是,打印出图片大小和颜色数

import os, struct

def bmpinfo(thePath):
    if os.path.isfile(thePath):
        with open(thePath,'rb') as f:
            bThirty = f.read(30)
            if len(bThirty) < 30:
                print('Not a bmp file!')
                return
            infos = struct.unpack('<ccIIIIIIHH', bThirty)
            if infos[0] != b'B' or infos[1] != b'M':
                print('Not a bmp file!')
                return
            print('The bmp file is %s * %s, and colors are %s.' % (infos[6], infos[7], infos[9]))
    else:
        print('File not exists!')

if __name__ == '__main__':
    print("Please input a bmp file's full path:")
    p = input()
    bmpinfo(p)

  • 1

Reply