如何使用纯Python创建BMP文件? [英] How do I create a BMP file with pure Python?

查看:527
本文介绍了如何使用纯Python创建BMP文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用纯Python创建黑白BMP文件.

I need to create a black and white BMP file with pure Python.

我阅读了有关维基百科的文章, BMP文件格式,但是我不擅长低级编程,想填补我的知识空白.

I read an article on wikipedia, BMP file format, but I am not good at low level programming and want to fill this gap in my knowledge.

问题是,如何创建具有像素矩阵的黑白BMP文件?我需要使用纯Python来执行此操作,而不要使用任何模块(如PIL).这只是为了我的教育.

So the question is, how do I create a black and white BMP file having a matrix of pixels? I need to do this with pure Python, not using any modules like PIL. It is just for my education.

推荐答案

这是单色位图的完整答案.

This is a complete answer for monochrome bitmaps.

import math, struct

mult4 = lambda n: int(math.ceil(n/4))*4
mult8 = lambda n: int(math.ceil(n/8))*8
lh = lambda n: struct.pack("<h", n)
li = lambda n: struct.pack("<i", n)

def bmp(rows, w):
    h, wB = len(rows), int(mult8(w)/8)
    s, pad = li(mult4(wB)*h+0x20), [0]*(mult4(wB)-wB)
    s = li(mult4(w)*h+0x20)
    return (b"BM" + s + b"\x00\x00\x00\x00\x20\x00\x00\x00\x0C\x00\x00\x00" +
            lh(w) + lh(h) + b"\x01\x00\x01\x00\xff\xff\xff\x00\x00\x00" +
            b"".join([bytes(row+pad) for row in reversed(rows)]))

例如:

FF XXXXXXXX
81 X......X
A5 X.X..X.X
81 X......X
A5 X.X..X.X
BD X.XXXX.X
81 X......X
FF XXXXXXXX

因此,将其编码为一系列行:

So, encoding this as a series of rows:

smile = [[0xFF], [0x81], [0xA5], [0x81], [0xA5], [0xBD], [0x81], [0xFF]]

通过以下方式呈现:

bmp(smile, 8)

请注意,程序员有责任确保所提供的每一行中都存在所需的字节数.

Note that it is the programmer's responsibility to ensure that the required number of bytes are present in each row supplied.

如果要更改它们,则在\ xff \ xff \ xff中指定黑色,而在以下\ x00 \ x00 \ x00中指定白色.

The black color is specified in the \xff \xff \xff and the white color is specified in the following \x00 \x00 \x00, should you want to change them.

这篇关于如何使用纯Python创建BMP文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆