Python下的图片编辑
Python下的图像处理
python代码
import struct
def read_bmp(test):
with open("test.bmp", "rb") as f:
# 读取文件头部信息
header = f.read(54)
# 解析文件头部信息
width = struct.unpack("<I", header[18:22])[0]
height = struct.unpack("<I", header[22:26])[0]
bits_per_pixel = struct.unpack("<H", header[28:30])[0]
# 计算每行像素所占字节数(包括对齐)
row_bytes = (bits_per_pixel * width + 31) // 32 * 4
# 初始化像素数据矩阵
pixels = [[(0, 0, 0) for _ in range(width)] for _ in range(height)]
# 跳至像素数据开始位置
f.seek(54)
# 逐行读取像素数据
for i in range(height):
# 每行按顺序读取像素值
for j in range(width):
b, g, r = struct.unpack("BBB", f.read(3))
pixels[i][j] = (r, g, b)
# 跳过对齐字节
f.read(row_bytes - width * 3)
return pixels, width, height
def write_bmp(file_path, pixels, width, height):
with open(file_path, "wb") as f:
# BMP文件头部信息
header = b"\x42\x4d" # BM
file_size = width * height * 3 + 54
header += struct.pack("<I", file_size)
header += b"\x00\x00\x00\x00"
data_offset = 54
header += struct.pack("<I", data_offset)
# BMP信息头信息
info_header_size = 40
planes = 1
bits_per_pixel = 24
compression = 0
image_size = width * height * 3
x_pixels_per_meter = 0
y_pixels_per_meter = 0
total_colors = 0
important_colors = 0
info_header = struct.pack("<IiiHHIIiiII", info_header_size, width, height, planes, bits_per_pixel,
compression, image_size, x_pixels_per_meter, y_pixels_per_meter, total_colors,
important_colors)
# 写入BMP文件头部信息和信息头信息
f.write(header)
f.write(info_header)
# 写入像素数据
for row in pixels:
for r, g, b in row:
f.write(struct.pack("BBB", b, g, r))
print("Write BMP file success!")
# 读取BMP图像文件
pixels, width, height = read_bmp("example.bmp")
# 在矩阵中绘制一条从左上角到右下角的红色直线
for i in range(height):
for j in range(width):
if i == j:
pixels[i][j] = (255, 0, 0)
# 将修改后的像素数据写入新的BMP文件
write_bmp("output.bmp", pixels, width, height)
但出现了一些问题导致输出的output.bmp无法打开,不知道是哪里出现了问题
![](https://img2023.cnblogs.com/blog/3263914/202310/3263914-20231023000631441-612151951.png)