Discuss / Python / 作业

作业

Topic source
def bmp_info(data):
    info = struct.unpack('<ccIIIIIIHH', data[0:30])
    return {"width": info[6], "height": info[7], "color": info[9]}

可以直接读取文件来获取文件的信息

import struct


def image_info(image_path):
    with open(image_path, "rb") as file:
        image_header = file.read(30)
        image_info = struct.unpack('<ccIIIIIIHH', image_header)
        return {
            "size": image_info[2],
            "width": image_info[6],
            "height": image_info[7],
            "color": image_info[9]
        }


file_paths = (
    r"C:\Users\user\Desktop\test_0.bmp",
    r"C:\Users\user\Desktop\test_16.bmp",
    r"C:\Users\user\Desktop\test_256.bmp",
    r"C:\Users\user\Desktop\test_24.bmp"
)
for file_path in file_paths:
    print(file_path, "\t", image_info(file_path))


# 输出结果
C:\Users\user\Miniconda3\envs\py3.7\python.exe C:/Users/zhenguozhao/PycharmProjects/test/test.py
C:\Users\user\Desktop\test_0.bmp      {'size': 47902, 'width': 819, 'height': 460, 'color': 1}
C:\Users\user\Desktop\test_16.bmp      {'size': 189638, 'width': 819, 'height': 460, 'color': 4}
C:\Users\user\Desktop\test_256.bmp      {'size': 378278, 'width': 819, 'height': 460, 'color': 8}
C:\Users\zhenguozhao\Desktop\test_24.bmp      {'size': 1131654, 'width': 819, 'height': 460, 'color': 24}

  • 1

Reply