如何在没有标题的情况下向bmp图像添加标题?

时间:2016-01-05 12:04:42

标签: python bitmap python-imaging-library pillow

我正在使用产品,我可以向它发送BMP文件,但它只接受没有标题的BMP,所以我删除了标题。 然而,该产品可以向我发送其BMP文件,我想在网页上显示它们,所以我需要重新创建标题以使其正常工作。

解决方案可能是将标题存储在我的文件系统或数据库中,但我想知道是否有重新创建标题的解决方案,例如pillow

目前我只打开我的BMP(24位,无标题)文件:

logo_file = open(django_settings.UPLOAD_DIR+'logos/1568/logo1-no-header.bmp', 'rb').read()

也许可以将二进制数据转换为像素并使用pillow创建新图像,插入像素并保存到BMP?

2 个答案:

答案 0 :(得分:0)

你看过construct了吗?它支持BMP。

我建议先看看这些早期的问题,但不一样,但有一些例子可以提供帮助。 how to create bmp file

答案 1 :(得分:0)

为了使用Pillow将24位/像素BMP的原始像素数据按到一个完整的图像文件中,需要做两件事:

  • 将图像上下翻转,因为BMP从下向上保存像素行,
  • 并重新排序像素组件,因为BMP以蓝色,绿色,红色顺序存储像素,但Pillow仅支持RGB顺序。

假设您在名为test.dat的文件中有33456个字节的原始像素数据:

#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from PIL import Image


def main():
    with open('test.dat', 'rb') as data_file:
        raw_data = data_file.read()
    red, green, blue = Image.frombytes('RGB', (164, 68), raw_data).split()
    image = Image.merge('RGB', (blue, green, red))
    image = image.transpose(Image.FLIP_TOP_BOTTOM)
    image.save('result.bmp')


if __name__ == '__main__':
    main()

这是一个创建示例test.dat的小程序:

#!/usr/bin/env python3
import base64
import gzip

DATA = b'''\
H4sIAOkP7VwC/+3c+1MTRxwA8L/C6g/9yVHbOnYqte2MVsfWajvTmSqSqbVSR6vVWq3QDsy09VFf
gPXFqxSIEEFGBEU0AqIICmgK6GREtEJCCAFFXjoghHtfQhcSIblcQhIud5vc7nx/Svb2Lvdh9767
e8PoKCylV68dRUUeJUMxs7u5Ad0HORTVxrkZilmD3UZ0K2RijbhlZY24ZWUNAn/1At0TmViDoHEz
ui0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Ndd92rZOhT3ptg/7JY9o8Ml7CdKP5I15e7XZMVpVbMBDGa05vgEMI75G9aGv
oFI+UUV6SM53FBC9Dl340LXJyqszsFDdUwiZ67SdHaOsIAn3oLy3hCBop+tUZGGudUZRgbt853Hp
2/Fdo4kEPuwot9rypLF+/eApK9WvIAY7iIF2kQPvb8Ff6LwMrO+J5NZrlDzWbx0ayW3gmTsb+lnX
ytvP4+CrzoGxr75Ml2YwN6m3mtRbRI72S5G6syv1eZ97GZJbP37uxPfh8ZHSxzR/Zt5Eu0Jn3rX/
STh+2NQldgfvKNslvrXp6lajL9wwDOOfjm+CfJGG1be7XeI+cI0nbWsw2etzVlqWJWKysPaRGwbr
B0+Z/7o99cTw0zzLKS/N9pw87x4t+WKaZNa+cEOeuZGMdWGCSyaWPKnZPWThfPvoOSsvaxt30TdT
csMM3drH8s2yccc6bx92+vZYJSnJpUpsPcb9g/HiFNzQQl9+yJOJZf3rlLZxXlVakSrZior01l5w
wwm9t4RnaeV+h1PmdkFLw7PnBYX1a269G24IoddkcjOxuQdHBjCnDY5+M/cxre1kkbWN21AYwcsN
G3RqDeW6peVabUGcU53D5aS0lw2RtXpLhxtuCPv15rzJp/CuC7hrhW35uLSzab51sy1QBeBuK1To
81bB/7xecmpsGFfV8SyTql1WzxgIXihlaZylMcgCZ0kzS70OEtL/UkvQ1tt6njU08NTmQHtYakMl
qAtnXWUfHPuYaP9a8AKe3Y7Qi09C9M4w0XmRMJ0jTPnwhlEVLNDlTxjO6E0yEP2V4vo0XJcEeQQF
dNcg9zFd0wrXYxpv/QdZC1WiL02upMVege51I9ygRNYClpsttO1lBhgnDqbzsFsblMGVh/cNW3qG
LBBeGNVbDbk1+UyN5nGCFAv5EnJrdtiAmAQbxg1ZEFsnIyAhuzYzAm+nxroQkMCr4iMdEELTAw8R
TUC4sS6ooJlXzQgloIV+0YDrUiUkxnQpYGqAILwv/wPSBv8IsIIAAA=='''


def main():
    with open('test.dat', 'wb') as file:
        file.write(gzip.decompress(base64.decodebytes(DATA)))


if __name__ == '__main__':
    main()