def __init__(self, rect, imgPATH, id): super().__init__() self.__original_image = Image(imgPATH, size=(rect.width, rect.height)).image.convert_alpha() self.bullets = [] self.distance_vector = pygame.Vector2(0, 0) self.safe_bullet_distance = 0 self.bullet_speed = 10 self.look_vector_bullet = pygame.Vector2(-7, 0) self.angle_speed = 3 self.angle = 90 self.victory_points = 0 self.is_alive = True self.death_gif = Gif(config.PATH_TO_EFFECTS + "\\smoke\\frames\\", [70, 70], 0.02) self.id = id self.current_speed = 10 self.position = pygame.Vector2() self.look_vector = pygame.Vector2() self.rect = pygame.Rect(0, 0, 0, 0) self.spawn() self.set_rect(rect) self.mask = pygame.mask.from_surface(self.__original_image) self.image_rect = self.image.get_rect()
def setup_players(self): self.hero_sprites.add( Player('Pacman', 290, 440, Gif('res/pacman.gif', (32, 32)))) for hero in self.hero_sprites: hero.move_area = hero.move_area player = Player('Blinky', 287, 199, Gif('res/blinky.gif', (32, 32))) player.ai = GhostAI.Blinky player.move_area = 4 self.ghost_sprites.add(player) player = Player('Clyde', 319, 259, Gif('res/clyde.gif', (32, 32))) player.ai = GhostAI.Clyde player.move_area = 5.5 self.ghost_sprites.add(player) player = Player('Inky', 255, 259, Gif('res/inky.gif', (32, 32))) player.ai = GhostAI.Inky player.move_area = 4.5 self.ghost_sprites.add(player) player = Player('Pinky', 287, 259, Gif('res/pinky.gif', (32, 32))) player.ai = GhostAI.Pinky player.hangOn = 0 player.move_area = 5.5 self.ghost_sprites.add(player) return self.hero_sprites, self.ghost_sprites
def test_inject_then_extract(self): for fname in self.fnames[:2]: mygif = Gif() mygif.read_from_file(fname) b = os.urandom(mygif.available_bytes() - 4) gif_inject(mygif, b) data = gif_extract(mygif) print(b.hex()) print(data.hex()) self.assertEqual(b, data)
def decode_route(): file = request.files['file'] encoded = Gif(KaitaiStream(BytesIO(file.read()))) res = decode(encoded) return {"message": res}
def copy_global_ct(inputgif): """ This function creates a copy of the global colour table :param inputgif: the input gif object :return: new table which is a deep copy of the global color table """ global_table = inputgif.global_color_table new_table = Gif.ColorTable(global_table._io) for i in global_table.entries: newcolor = Gif.ColorTableEntry(None) newcolor.red = i.red newcolor.green = i.green newcolor.blue = i.blue new_table.entries.append(newcolor) return new_table
def encode_route(): file = request.files['file'] gif = Gif(KaitaiStream(BytesIO(file.read()))) message = request.form["message"] gif = encode(count_available_storage(gif), message, gif) res = gif_to_bytearray(gif) return send_file(io.BytesIO(bytes(res)), mimetype='image/gif')
def test_encode1(self): # test the encoded/compressed indexes that it is the same as earlier new_subblocks = encode(self.indexes) for i in new_subblocks: self.assertIsInstance(i, Gif.Subblock) for i in self.gif.blocks: if i.block_type == Gif.BlockType.local_image_descriptor: i.body.image_data.subblocks.entries = new_subblocks gif2 = Gif.from_file("./test_src/sample_1.gif") self.assertEqual(gif_to_bytearray(self.gif), gif_to_bytearray(gif2))
def setUp(self): # set up with small gif file and known index values self.gif = Gif.from_file("./test_src/sample_1.gif") self.indexes = [ '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '1', '1', '1', '0', '0', '0', '0', '2', '2', '2', '1', '1', '1', '0', '0', '0', '0', '2', '2', '2', '2', '2', '2', '0', '0', '0', '0', '1', '1', '1', '2', '2', '2', '0', '0', '0', '0', '1', '1', '1', '2', '2', '2', '2', '2', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '1', '1', '1', '1', '1' ]
def checkGCT(inputgif): """ This function checks if the GIF has GCT and if it is of size 256 Called in count_available_storage :param inputgif: GIF object :return: GIF object """ flag = inputgif.logical_screen_descriptor.flags if (flag & 128) != 0: # if there is GCT global_table = inputgif.global_color_table if len(global_table.entries) == 256: # if size of GCT is 256 return inputgif else: # if size not 256 old_table = global_table.entries new_table = Gif.ColorTable( global_table._io) # create new empty table for i in range(256): if i < len(old_table): # append the old table RGB values newcolor = Gif.ColorTableEntry(None) newcolor.red = old_table[i].red newcolor.green = old_table[i].green newcolor.blue = old_table[i].blue new_table.entries.append(newcolor) else: # create empty RGB values for new entries newcolor = Gif.ColorTableEntry(None) newcolor.red = 0 newcolor.green = 0 newcolor.blue = 0 new_table.entries.append(newcolor) inputgif.global_color_table = new_table inputgif.logical_screen_descriptor.flags = 247 # change the flag value to indicate correct size of gct # else no gct just return inputgif return inputgif
def test_encode2(self): # test that changing the indexes and compressing it will still work self.indexes[0] = '2' self.indexes[6] = '1' new_subblocks = encode(self.indexes) for i in self.gif.blocks: if i.block_type == Gif.BlockType.local_image_descriptor: i.body.image_data.subblocks.entries = new_subblocks write_to_file(self.gif, "./test_src/res_2.gif") gif2 = Gif.from_file("./test_src/res_2.gif") for i in gif2.blocks: if i.block_type == Gif.BlockType.local_image_descriptor: resulting_index = decode(i.body.image_data) self.assertEqual(resulting_index, self.indexes)
async def g(ctx, x, r = None): x = x.upper() embed = discord.Embed(title = x, color = discord.Colour.teal()) x= x.lower() y = ctx.author.mention c = Gif(y, x) # file = discord.File(y+'.gif') # b = 'attachment://'+y+'.gif' # embed.set_image(url = b) if r == None: embed.add_field(name = "\u200b", value = y+" "+x, inline=True) else: embed.add_field(name = "\u200b", value = y+" "+x+" "+r, inline = True) embed.set_image(url = c) await ctx.send(embed = embed)
def __init__(self, name: str, x, y, img: Gif): pygame.sprite.Sprite.__init__(self) self.name = name self.gif = img # Copy, not reference self.image = img.get_frame() # setting position self.rect = self.image.get_rect() self.rect.left = x self.rect.top = y # setup some attributes # Input Ahead self.move_buffer = util.Vector2.zero() # Current movement self.move_dir = util.Vector2.zero() # MoveSpeed self.move_area = 6 # Wall Detect Speed self.move_dArea = 30 # GhostAI self.AIProgram = None
elif code == stop: break if code < next_code: index_list = code_table[code] for c in index_list: index_stream.append(c) if prevCode != clear: code_table.append(code_table[prevCode] + (index_list[0], )) next_code += 1 else: index_list = code_table[prevCode] for c in index_list: index_stream.append(c) index_stream.append(index_list[0]) code_table.append(index_list + (index_list[0], )) next_code += 1 prevCode = code return index_stream if __name__ == "__main__": fname = '../gifs/sample_2_animation.gif' mygif = Gif() mygif.read_from_file(fname) print('available bytes in first frame = {}'.format( mygif.get_frames()[0].available_bytes())) print('total available bytes = {}'.format(mygif.available_bytes()))
from gif import Gif g = Gif('gif.gif') img = g.extend(g.imgs[0], (20, 40, 60, 80), 0) img.save('image/1.png') img = g.tap(img, 'Hello!', local=(10, 20), size=30) img.save('image/2.png') imgs = g.mextend(g.imgs, (20, 10, 20)) g.save_gif(imgs, 'image/3.gif') imgs = g.mtap(imgs, '谢谢老哥', local=(10, 5), size=19) g.save_gif(imgs, 'image/4.gif')
def test_write_to_file(self): # test that writing to file does not change the gif write_to_file(self.gif, "./test_src/res_1.gif") res_gif = Gif.from_file("./test_src/res_1.gif") self.assertEqual(gif_to_bytearray(self.gif), gif_to_bytearray(res_gif))
res += bytearray(c.red.to_bytes(1, 'little')) res += bytearray(c.green.to_bytes(1, 'little')) res += bytearray(c.blue.to_bytes(1, 'little')) res += bytearray( i.body.image_data.lzw_min_code_size.to_bytes(1, 'little')) for j in i.body.image_data.subblocks.entries: res += bytearray(j.num_bytes.to_bytes(1, 'little')) res += bytearray(j.bytes) with open(filename, 'wb+') as f: f.write(res) print(len(res)) if __name__ == "__main__": data1 = Gif.from_file("../../../Downloads/safe_image.gif") data2 = Gif.from_file( "../../../Downloads/tumblr_pvk36wTOsT1ytp1fjo1_540.gif") # print(data1.hdr.magic) # print(data1.hdr.version) # color_table1 = data1.global_color_table.entries # color_table2 = data2.global_color_table.entries # for i in range(1, len(color_table1)): # color1 = color_table1[i] # color2 = color_table2[i] # # print(i, "\t", color1.red, color1.green, color1.blue, "\t", color2.red, color2.green, color2.blue) # print(data2.logical_screen_descriptor.has_color_table)
Usage: gif-audio-add.py <input.gif> <input.wav> Creates new file named `<input>.a.gif` which has the recommended file extension for Audio GIFs. """ raise SystemExit output_file_path = os.path.splitext(original_gif_file_path)[0] + ".a.gif" print "Output filepath:", output_file_path if os.path.exists(output_file_path): print "Output file path exists, not overwriting. Stopping." raise SystemExit data = Gif.from_file(original_gif_file_path) calculated_offset = 0 #print data.hdr.magic, # 3 bytes #print data.hdr.version # 3 bytes calculated_offset += (3 + 3) # logical screen descriptor # 7 bytes calculated_offset += 7 if data.logical_screen_descriptor.has_color_table: global_color_table_byte_size = len(data._raw_global_color_table)
def encode(index_stream): """ LZW Decompression for Kaitai GIF image data @author: Bill Ivan Kooslarto - 28694120 @param image_data: a Kaitai Gif.ImageData object @return: array of indexes """ # initialise LZW table max_index = max([int(i, base=10) for i in index_stream]) min_code = math.ceil(math.log(max_index, 2)) if min_code == 1: min_code = 2 lzw_table_size = (2 ** min_code) + 2 lzw_table = [[str(i)] for i in range(lzw_table_size)] lzw_table[-1] = [EOI] lzw_table[-2] = [CC] bits_to_decode = min_code + 1 code_stream = bin(lzw_table.index([CC]))[2:] index_buffer = [index_stream[0][:]] # LZW compress the index array to code stream for i in range(1, len(index_stream)): K = [index_stream[i][:]] try: lzw_table.index(index_buffer + K) index_buffer += K if i == len(index_stream) - 1: code_stream = bin(lzw_table.index(index_buffer))[2:].zfill(bits_to_decode) + code_stream except ValueError: lzw_table.append(index_buffer + K) code_stream = bin(lzw_table.index(index_buffer))[2:].zfill(bits_to_decode) + code_stream index_buffer = K if len(lzw_table) > 2 ** bits_to_decode: bits_to_decode += 1 # add end of information code code_stream = bin(lzw_table.index([EOI]))[2:] + code_stream # split the code stream into subblocks code_len = len(code_stream) i = code_len bytes_list = [] while i >= 0: if i < 8: byte_string = ("0"*(8-i)) + code_stream[:i] else: byte_string = code_stream[i-8:i] bytes_list = [int(byte_string, 2).to_bytes(len(byte_string)//8, byteorder='little')] + bytes_list i -= 8 max_subblock_len = 255 new_entries = [] temp_byte = bytearray() byte_count = 0 for i in range(len(bytes_list)): temp_byte = bytes_list[i] + temp_byte byte_count += 1 if byte_count == max_subblock_len or i == len(bytes_list) - 1: new_subblock = Gif.Subblock(None) new_subblock.num_bytes = byte_count new_subblock.bytes = temp_byte new_entries.append(new_subblock) byte_count = 0 new_subblock = Gif.Subblock(None) new_subblock.num_bytes = 0 new_subblock.bytes = b'' new_entries.append(new_subblock) return new_entries
import unittest from preprocess import * from gif import Gif # Author : Jia Qin Choong # Usage : Testing functions in preprocess.py path = "./test_src/levi.gif" inputgif = Gif.from_file(path) class Test_Preprocess(unittest.TestCase): def test_capacity(self): # check to see if the count returned a value > 0 self.assertGreater(count_available_storage(inputgif), 0, "Failed to check capacity") def test_get_lct_index(self): # check to see if the number of frames are obtained properly indexlist = get_lct_index(inputgif) blocks = inputgif.blocks count = 0 for i in range(len(blocks)): if str(blocks[i].block_type) == "BlockType.local_image_descriptor": count += 1 self.assertEqual(len(indexlist), count, "Failed to get lct index list") def test_setlocalCT(self): # check if all the local color table flag has been set to 135 indexlist = set_local_color_table(inputgif) count = 0 blocks = inputgif.blocks # the frames are stored in blocks
class Player(Entity): def __init__(self, rect, imgPATH, id): super().__init__() self.__original_image = Image(imgPATH, size=(rect.width, rect.height)).image.convert_alpha() self.bullets = [] self.distance_vector = pygame.Vector2(0, 0) self.safe_bullet_distance = 0 self.bullet_speed = 10 self.look_vector_bullet = pygame.Vector2(-7, 0) self.angle_speed = 3 self.angle = 90 self.victory_points = 0 self.is_alive = True self.death_gif = Gif(config.PATH_TO_EFFECTS + "\\smoke\\frames\\", [70, 70], 0.02) self.id = id self.current_speed = 10 self.position = pygame.Vector2() self.look_vector = pygame.Vector2() self.rect = pygame.Rect(0, 0, 0, 0) self.spawn() self.set_rect(rect) self.mask = pygame.mask.from_surface(self.__original_image) self.image_rect = self.image.get_rect() image_rect = None __original_image = None image = None bullets = [] distance_vector = None safe_bullet_distance = 0 bullet_speed = 10 look_vector_bullet = None angle_speed = 3 angle = 90 victory_points = 0 is_alive = True death_gif = None id = 0 mask = None def reset(self): self.victory_points = 0 if self.death_gif: self.death_gif.stop() def spawn(self): self.image = self.__original_image.copy() self.angle = 0 self.set_angle(0) self.look_vector = pygame.Vector2(-self.current_speed, 0) self.look_vector_bullet = pygame.Vector2(-self.bullet_speed, 0) self.is_alive = True self.bullets.clear() if self.death_gif: self.death_gif.stop() def set_image(self, img_path): self.__original_image = Image(img_path, size=(self.__original_image.get_rect().width, self.__original_image.get_rect().height)).image.convert_alpha() self.image = pygame.transform.rotate(self.__original_image, self.angle) def set_position(self, x, y): self.set_rect(self.image.get_rect(center=(x, y))) def set_rect(self, rect): self.rect = self.image.get_rect(center=(rect.x, rect.y)) self.position = pygame.Vector2(rect.x, rect.y) self.distance_vector = pygame.math.Vector2(0, -(self.rect.height + self.safe_bullet_distance) // 2) def set_save_distance(self, distance): self.safe_bullet_distance = distance self.distance_vector = pygame.math.Vector2(0, -(self.rect.height + self.safe_bullet_distance) // 2) def get_barrel_end(self): return self.rect.center + self.distance_vector.rotate(-self.angle) def set_speed(self, speed, bullet_speed): self.current_speed = speed self.bullet_speed = bullet_speed self.look_vector = pygame.Vector2(-self.current_speed, 0) self.look_vector_bullet = pygame.Vector2(-self.bullet_speed, 0) def add_bullet(self): if len(self.bullets) < config.max_ball_count and self.is_alive: self.bullets.append(Bullet(pygame.Rect(self.get_barrel_end().x + config.ball_radius // 2, self.get_barrel_end().y, config.ball_radius, config.ball_radius), self.look_vector_bullet, self.id)) def kill(self): self.is_alive = False self.death_gif.start_drawing() def check_for_leave_of_screen(self): width, height = config.window_size # height - y if self.rect.top < 0 or self.rect.bottom < 0 and self.look_vector.y < 0: self.rect.top = 0 self.position = pygame.Vector2(self.rect.center) elif self.rect.bottom > height or self.rect.top > height and self.look_vector.y > 0: self.rect.bottom = height self.position = pygame.Vector2(self.rect.center) # width - x if self.rect.left < 0 or self.rect.right < 0 and self.look_vector.x < 0: self.rect.left = 0 self.position = pygame.Vector2(self.rect.center) elif self.rect.right > width or self.rect.left > width and self.look_vector.x > 0: self.rect.right = width self.position = pygame.Vector2(self.rect.center) def wall_collision_angle_handler(self, value): angle = self.angle + value * 2 look_vector = pygame.Vector2(*self.look_vector) look_vector.rotate_ip(-value) image = pygame.transform.rotate(self.__original_image, angle) temp_rect = self.rect temp_rect = image.get_rect(center=temp_rect.center) for wall in lvlManager.levels[lvlManager.current_level_index].walls: offset = (int(temp_rect.topleft[0] - wall.rect.x), int(temp_rect.topleft[1] - wall.rect.y)) result = wall.mask.overlap(self.mask, offset) if result: return result return False def wall_collision_handler(self, value): self.mask = pygame.mask.from_surface(self.image) topleft = self.rect.topleft + value for wall in lvlManager.levels[lvlManager.current_level_index].walls: offset = (int(topleft[0] - wall.rect.x), int(topleft[1] - wall.rect.y)) result = wall.mask.overlap(self.mask, offset) if result: return True return False def set_angle(self, value): self.angle += value self.look_vector.rotate_ip(-value) self.look_vector_bullet.rotate_ip(-value) self.image = pygame.transform.rotate(self.__original_image, self.angle) self.rect = self.image.get_rect(center=self.rect.center) self.check_for_leave_of_screen() def move_forward(self): if self.is_alive and not self.wall_collision_handler(self.look_vector): self.position += self.look_vector self.rect.center = self.position def move_back(self): if self.is_alive and not self.wall_collision_handler(-self.look_vector): self.position -= self.look_vector self.rect.center = self.position def move_left(self): if self.is_alive and not self.wall_collision_angle_handler(self.angle_speed): self.set_angle(self.angle_speed) def move_right(self): if self.is_alive and not self.wall_collision_angle_handler(-self.angle_speed): self.set_angle(-self.angle_speed)
def calculate_route(): file = request.files['file'] data = Gif(KaitaiStream(BytesIO(file.read()))) capacity = count_available_storage(data) return {"capacity": capacity}
def __init__(self, bot: commands.Bot): self.bot = bot # For voice messages: self.botTalk = BotTalk() # For gif messages: bot.add_cog(Gif(bot))