2015-05-27 3 views
-1

Я хочу, чтобы создать BMP изображение в питоне без использования какого-либо встроенное в библиотеке, изображение, как это:питон код без библиотек

enter image description here

, пожалуйста, как я могу это сделать?

+0

Можете ли вы дать [Minimal, полный и Подтверждаемый пример] (http://stackoverflow.com/help/mcve) о том, что вы хотите сделать? или код, который вы пробовали до сих пор? – Kasramvd

+2

Если вы объясните, почему вы не хотите использовать «встроенную библиотеку», люди могут понять, о чем вы действительно просите. Если это только для образовательных целей, прочитайте это: http://en.wikipedia.org/wiki/BMP_file_format – folkol

ответ

8

Используя BMP file format вы можете просто создать собственный BMP файл:

import math 
import struct 

width = 200 
height = 200 
bits_per_pixel = 24 

# bitmap file header 
data = 'BM' # Windows 3.1x, 95, NT, ... etc. 
data += struct.pack('i', 26 + bits_per_pixel/8 * width * height) # The size of the BMP file in bytes = header + (color bytes * w * h) 
data += struct.pack('h', 0) # Reserved 
data += struct.pack('h', 0) # Reserved 
data += struct.pack('i', 26) # The offset, i.e. starting address, of the byte where the bitmap image data (pixel array) can be found. 
# bitmap header (BITMAPCOREHEADER) 
data += struct.pack('i', 12) # The size of this header (12 bytes) 
data += struct.pack('h', width) # width 
data += struct.pack('h', height) # height 
data += struct.pack('h', 1) # The number of color planes, must be 1 
data += struct.pack('h', bits_per_pixel) # The number of bits per pixel, which is the color depth of the image. Typical values are 1, 4, 8, 16, 24 and 32. 

def rgb_to_bmp_data(r, g, b): 
    return chr(b) + chr(g) + chr(r) 

row_bytes = width * (bits_per_pixel/8) 
row_padding = int(math.ceil(row_bytes/4.0)) * 4 - row_bytes 

for y in xrange(height - 1, -1, -1): 
    for x in xrange(width): 
     if (y/25) % 2: 
      if (x/25) % 2: 
       data += rgb_to_bmp_data(255, 255, 255) 
      else: 
       data += rgb_to_bmp_data(0, 0, 0) 
     else: 
      if (x/25) % 2: 
       data += rgb_to_bmp_data(0, 0, 0) 
      else: 
       data += rgb_to_bmp_data(255, 255, 255) 
    # add padding 
    data += '\x00' * row_padding 

with open('out.bmp', 'wb') as f: 
    f.write(data) 

В результате изображение близко к тому, что вам нужно:

enter image description here

Смежные вопросы