def writeImage(self, o_image): oBmp = bmp.Bmp() oBmp.fromBmp(o_image.data_s) ## User can assign new bitmap, so reload image parameters from it. o_image.initFromBmp(oBmp) nWidth = o_image.width_n assert nWidth <= 256 if 256 == nWidth: nWidth = 0 self.write('<B', nWidth) nHeight = o_image.width_n assert nHeight <= 256 if 256 == nHeight: nHeight = 0 self.write('<B', o_image.height_n) if 256 == o_image.colors_n: o_image.colors_n = 0 self.write('<B', o_image.colors_n) self.write('<B', 0) self.write('<H', o_image.planes_n) self.write('<H', o_image.bpp_n) self.writeSize('<I', o_image.index_n) self.writeOffset('<I', o_image.index_n) self.writeArrayEnd(oBmp.toIco(), n_id=o_image.index_n)
def addFromRaw(self, s_data, n_width, n_height, n_bpp): assert 32 == n_bpp oBmp = bmp.Bmp() oBmp.fromRaw(s_data, n_width, n_height, n_bpp) oImage = Image() oImage.initFromBmp(oBmp) self.images_l.append(oImage)
def image(self): if hasattr(self, '_m_image'): return self._m_image if hasattr(self, '_m_image') else None if self.image_size != 4294967295: _pos = self._io.pos() self._io.seek(self.image_start_address) self._raw__m_image = self._io.read_bytes((self.image_size * 512)) _io__raw__m_image = KaitaiStream(BytesIO(self._raw__m_image)) self._m_image = bmp.Bmp(_io__raw__m_image) self._io.seek(_pos) return self._m_image if hasattr(self, '_m_image') else None
def images(self): if hasattr(self, '_m_images'): return self._m_images if hasattr(self, '_m_images') else None _pos = self._io.pos() self._io.seek((self.story_start_address + ((1 + self.navigation.image_start_sector) * 512))) self._raw__m_images = self._io.read_bytes( (self.navigation.image_size * 512)) _io__raw__m_images = KaitaiStream(BytesIO(self._raw__m_images)) self._m_images = bmp.Bmp(_io__raw__m_images) self._io.seek(_pos) return self._m_images if hasattr(self, '_m_images') else None
def addFromBmp( self, ##i Image data as loaded from |.bmp| file. s_data, ##i If specified, image's 'bits per pixel' value will be converted ## to specified. Used if image is programmatically generated (for ## expample, via PIL) and generator can't produce required bits per ## pixel for .bmp format (for example, PIL can't create 4 bits per ## pixel BMP). n_bpp=None): oBmp = bmp.Bmp() oBmp.fromBmp(s_data, n_bpp) oImage = Image() oImage.initFromBmp(oBmp) self.images_l.append(oImage)
def readImage(self): oImage = Image() oImage.width_n = self.read('<B') if 0 == oImage.width_n: oImage.width_n = 256 oImage.height_n = self.read('<B') if 0 == oImage.height_n: oImage.height_n = 256 oImage.colors_n = self.read('<B') assert 0 == self.read('<B') oImage.planes_n = self.read('<H') assert oImage.planes_n in [0, 1] oImage.bpp_n = self.read('<H') nData = self.read('<I') nOffset = self.read('<I') self.push(nOffset) oImage.data_s = self.readArray(nData) self.pop() ## .ico don't have any means to distinguish BMP and PNG data, so ## PNG is detected by 8-byte signature. PNG_MAGIC = '\x89\x50\x4E\x47\x0D\x0A\x1A\x0A' if nData > 8 and oImage.data_s.startswith(PNG_MAGIC): oImage.png_f = True else: oImage.png_f = False ## Read .ico version of BMP file (with doubled height, ## 'AND' transparency image etc) and convert to a BMP file data so ## it can be writen back to valid .bmp file. oBmp = bmp.Bmp() oBmp.fromIco(oImage.data_s) ##! Otherwrite image header data from |BMP| file structure, since ## it can be corrpupted: for example, |bpp| value can be 0. oImage.initFromBmp(oBmp) return oImage
def gif_to_bmp(file_name): file = open(file_name, 'rb') reader = gif.Reader() reader.feed(file.read()) if reader.has_screen_descriptor(): k = 0 width = reader.width height = reader.height for block in reader.blocks: if isinstance(block, gif.Image): pixels = block.get_pixels() if len(pixels) >= width * height: c = bmp.Bmp(height, width) for i in range(height): for j in range(width): # Заполняем ее цветами color_number = pixels[i * width + j] if color_number in block.color_table: cc = block.color_table[color_number] else: cc = reader.color_table[color_number] c.set_pixel(i, j, cc) c.write_to_file('test' + str(k) + '.bmp') k += 1
def read_from_file(self, file_name): with open(file_name, 'rb') as gif_byte: self.gif_arr = gif_byte.read() self.version = self.gif_arr[:6] # Версия self.width = struct.unpack('H', self.gif_arr[6:8])[0] self.height = struct.unpack('H', self.gif_arr[8:10])[0] for_flags = self.gif_arr[10] self.ct = (for_flags >> 7) & 1 self.color = (for_flags >> 4) & 7 self.sf = (for_flags >> 3) & 1 self.size_color = for_flags & 7 self.sreen_coolor = self.gif_arr[11] self.r = self.gif_arr[12] array_shift = 13 if self.ct: n = 2**(self.size_color + 1) self.global_color_table = [0 * i for i in range(n)] for i in range(n): offset = 13 + i * 3 (red, green, blue) = struct.unpack('BBB', self.gif_arr[offset:offset + 3]) self.global_color_table[i] = (blue, green, red) array_shift = 13 + n * 3 num_of_img = 0 while True: block_type = self.gif_arr[array_shift] if block_type == 0x21: #EXTENSION start_of_subblock = array_shift + 2 while self.gif_arr[start_of_subblock] != 0: start_of_subblock += self.gif_arr[start_of_subblock] + 1 array_shift = start_of_subblock + 1 elif block_type == 0x2c: #IMAGE width = struct.unpack( 'H', self.gif_arr[array_shift + 5:array_shift + 7])[0] height = struct.unpack( 'H', self.gif_arr[array_shift + 7:array_shift + 9])[0] for_flags = self.gif_arr[array_shift + 9] ct = (for_flags >> 7) & 1 if ct != 0: local_pallete = [] colors = 1 << ((for_flags & 7) + 1) for i in range(colors): (red, green, blue) = struct.unpack( 'BBB', self.gif_arr[array_shift + 10 + 3 * i:array_shift + 10 + 3 * i + 3]) local_pallete.append((blue, green, red)) array_shift += 3 * colors mc = self.gif_arr[array_shift + 10] # начальный размер LZV кода size_of_block = self.gif_arr[array_shift + 11] array_shift += 12 decoder = LZWDecoder(mc + 1) while size_of_block > 0: decoder.feed(self.gif_arr, array_shift, size_of_block) array_shift += size_of_block size_of_block = self.gif_arr[array_shift] array_shift += 1 _bmp = bmp.Bmp(height, width) for i in range(height): for j in range(width): _bmp.graphics[(height - i - 1) * width + j] = self.global_color_table[ decoder.values[width * i + j]] _bmp.write_to_file("test1_%d.bmp" % num_of_img) # выводим bmp num_of_img += 1 elif block_type == 0x3b: #TRAILER break
import gif_with_bmp import bmp import gif import math import myGif # Пример 1: Считываем тестовый файл, созданый в Paint, и записываем получившиеся данные в другой файл s = bmp.Bmp(2, 2) s.read_from_file('abc.bmp') s.write_to_file('cba.bmp') # Пример 2: Создаем bmp width = 8 height = 5 c = bmp.Bmp(height, width) for i in range(height): for j in range(width): if i == j: c.set_pixel(i, j, (0, 0, 150)) c.set_pixel(0, 0, (0, 150, 0)) c.write_to_file('artificial.bmp') # Пример 3: Создаем анимированную гифку BLACK = 0 WHITE = 1 RED = 2 GREEN = 3 BLUE = 4
def alpha(self): oBmp = bmp.Bmp() oBmp.fromBmp(self.data_s) return oBmp.alpha()
def bmp_to_gif(list_of_files): if len(list_of_files) == 0: print('Список пустой') return 0 s = bmp.Bmp(2, 2) s.read_from_file(list_of_files[0]) width = s.width height = s.height colors = [0] * (s.width * s.height) colors_dict = {} background_color = 0 version = gif.Version.GIF89a filename = 'test.gif' writer = gif.Writer(open(filename, 'wb')) writer.write_header(version) # создание палитры k = 0 for file_name in list_of_files: f = bmp.Bmp(2, 2) f.read_from_file(file_name) for pixel in f.graphics: pixel_from_color = (pixel[2], pixel[1], pixel[0]) if pixel_from_color not in colors: colors[k] = pixel_from_color k += 1 colors = colors[:k] # перенос палитры в словарь для быстрого доступа for i, color in enumerate(colors): colors_dict[color] = i if len(colors) > 0: depth = math.ceil(math.log2(len(colors))) writer.write_screen_descriptor(width, height, has_color_table=True, depth=depth, background_color=background_color) writer.write_color_table(colors, depth) else: writer.write_screen_descriptor(width, height, background_color=background_color) writer.write_netscape_extension(loop_count=0) for file_name in list_of_files: writer.write_graphic_control_extension(delay_time=50) f = bmp.Bmp(2, 2) f.read_from_file(file_name) graphics_for_gif = f.graphics.copy() for i in range(height): for j in range(width): graphics_for_gif[(height - i - 1) * width + j] = f.graphics[width * i + j] number_in_colors_for_pixel = [ colors_dict[(pixel[2], pixel[1], pixel[0])] for pixel in graphics_for_gif ] writer.write_image(width, height, depth, number_in_colors_for_pixel) writer.write_trailer()