'Create a Bitmap in python

I need to create a bitmap in python but I know:

  • bitmap pixel values
  • width
  • height
  • color planes
  • bits per pixel

I've already tried using PIL.Image but it doesn't let you choose an arbitrary bpp value (for instance I need 4 bpp which is not present in the supported modes).



Solution 1:[1]

If this is for fitting a maximum of information into available memory and you do not need display, load or save in a 4 bpp format that other applications can handle you could just use 8 bpp with half the width and wrap the two functions getpixel() and putpixel() to access or modify the respective halves of the 8 bits at (x//2, y), i.e. value >> 4 and value & 15, depending on whether x & 1 == 0. The function paste() can also easily be wrapped for x & 1 == 0 and even width. For other x or odd width, paste() takes a bit of effort to shift the bits into the right positions. Similarly, 2 bpp can use x//4.

For bit depths that are not a power of 2, one will want to go with the greatest depth available, e.g. an 8 bpp pixel could only store 2 pixels with 3 bpp but 64 bpp could store 21 such pixels, improving efficiency by 31%.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joachim Wagner