uccjshrimpton

BMP Interpreter

Jul 17th, 2016
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. from tkinter import *
  2. from tkinter.filedialog import askopenfile
  3. canvas_exists = False
  4.  
  5. def get_file():
  6.     image_file = askopenfile(parent=main_window, title='Select a Bitmap File')
  7.     image_file = open(image_file.name, "rb")
  8.     all_bytes = list(image_file.read())
  9.  
  10.     for index, byte in enumerate(all_bytes):
  11.         all_bytes[index] = str(hex(byte)[2:])
  12.  
  13.     # [x:x:-1] = start, end, steps
  14.     offset = int(str("".join(all_bytes[13:9:-1])), 16)
  15.     width = int(str("".join(all_bytes[21:17:-1])), 16)
  16.     height = int(str("".join(all_bytes[25:21:-1])), 16)
  17.     depth = int(str("".join(all_bytes[29:27:-1])), 16)
  18.  
  19.     print("Offset:", offset)
  20.     print("Width:", width)
  21.     print("Height:", height)
  22.     print("Depth:", depth)
  23.  
  24.     # pixel data stored from bottom right to top left
  25.     all_pixel_data = all_bytes[offset:]
  26.     map_bits(width, height, depth, all_pixel_data)
  27.  
  28. def map_bits(width, height, depth, all_pixel_data):
  29.     count = 0
  30.     pixel_data = []
  31.     horizontal_line = []
  32.     bit_map = []
  33.  
  34.     for byte in all_pixel_data:
  35.         if len(byte) < 2:
  36.             byte = "0" + byte
  37.         pixel_data.append(byte)
  38.         count += 1
  39.  
  40.         if count == 3:
  41.             count = 0
  42.  
  43.             pixel_data.append("#")
  44.             pixel_data = reversed(pixel_data)
  45.             horizontal_line.append("".join(pixel_data))
  46.             pixel_data = []
  47.  
  48.             if len(horizontal_line) == width:
  49.                 bit_map.insert(0, horizontal_line)
  50.                 horizontal_line = []
  51.     plot_image(width, height, depth, bit_map)
  52.  
  53. def plot_image(width, height, depth, bit_map):
  54.     global canvas_exists
  55.     global canvas_image
  56.     if canvas_exists == False:
  57.         canvas_image = Canvas(main_window, width=width, height=height)
  58.         canvas_image.pack()
  59.         canvas_exists = True
  60.  
  61.     else:
  62.         canvas_image.delete("all")
  63.  
  64.     for v_pixel in range(height):
  65.         for h_pixel in range(width):
  66.             canvas_image.create_rectangle(h_pixel, v_pixel, h_pixel, v_pixel, outline=bit_map[v_pixel][h_pixel])
  67.         canvas_image.update()
  68.  
  69. main_window = Tk()
  70. main_window.title("Bitmap Interpreter")
  71.  
  72. button_open = Button(main_window, text="Open Bitmap", command=get_file)
  73. button_open.pack()
  74.  
  75. main_window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment