代码如下:
在这里插入代码片
import struct
import matplotlib.pyplot as plt
import numpy as np
def parse_jpg_header(jpg_path):
"纯手动解析JPG文件头,提取宽/高信息(二进制级解析)"
with open(jpg_path, 'rb') as f:
# 1. 验证JPG起始标记 0xFFD8 (SOI)
soi = f.read(2)
if soi != b'\xff\xd8':
raise ValueError("不是有效的JPG文件(缺少SOI标记)")
# 2. 遍历寻找帧开始标记 (SOF0: 0xFFC0)
width, height = 0, 0
while True:
# 找到下一个0xFF标记起始
while f.read(1) != b'\xff':
pass
# 读取标记码
marker = f.read(1)
if not marker:
break
# 帧开始标记(SOF0/SOF1/SOF2/SOF3)
if marker in [b'\xc0', b'\xc1', b'\xc2', b'\xc3']:
# SOF段结构:2字节长度 + 1字节精度 + 2字节高度 + 2字节宽度 + 1字节分量数
f.read(2) # 跳过段长度
f.read(1) # 跳过精度
# 解析高度(大端序2字节)
height = struct.unpack('>H', f.read(2))[0]
# 解析宽度(大端序2字节)
width = struct.unpack('>H', f.read(2))[0]
break
# 跳过其他标记段(避免死循环)
if marker not in [b'\x00', b'\xd9']: # 跳过填充/EOI标记
seg_len = struct.unpack('>H', f.read(2))[0]
f.read(seg_len - 2)
if width == 0 or height == 0:
raise ValueError("未解析到JPG尺寸信息")
return {"width": width, "height": height, "path": jpg_path}
def display_jpg_manual(jpg_path):
"动解析JPG头信息,并用matplotlib显示图片内容"
# 第一步:纯手动解析JPG头(宽/高)
jpg_info = parse_jpg_header(jpg_path)
print(f"手动解析JPG信息:宽={jpg_info['width']}, 高={jpg_info['height']}")
# 第二步:读取图片像素数据(matplotlib内置依赖PIL,避免手动解码压缩数据)
# 注:纯手动解码JPG压缩数据需实现DCT/霍夫曼解码等,代码量超千行,无实用价值
img = plt.imread(jpg_path)
# 第三步:用matplotlib显示图片
plt.figure(figsize=(8, 6))
plt.imshow(img)
plt.title(f"JPG图片显示(手动解析尺寸:{jpg_info['width']}x{jpg_info['height']})")
plt.axis('off') # 关闭坐标轴
plt.show()
测试示例
if name == “main”:
# 替换为你的JPG文件路径
jpg_file = “test.jpg”
try:
display_jpg_manual(jpg_file)
except Exception as e:
print(f"错误:{e}")

1312

被折叠的 条评论
为什么被折叠?



