| 30 | |
| 31 | |
| 32 | class Png: |
| 33 | default_alpha = 0 |
| 34 | grayscale_palette = { |
| 35 | 1: [[0 for _ in range(3)], [255 for _ in range(3)] ], |
| 36 | 2: [[255 // 3 * i for _ in range(3)] for i in range(4)], |
| 37 | 4: [[255 // 15 * i for _ in range(3)] for i in range(16)], |
| 38 | } |
| 39 | channels_lookup = (1, None, 3, 1, 2, None, 4) |
| 40 | default_dir = "./" |
| 41 | |
| 42 | def __init__(self, filename, dir=None, pickle_dir="", |
| 43 | from_pickle=True, to_pickle=True, crc=False) -> None: |
| 44 | ''' |
| 45 | filename can be with or without ".png". |
| 46 | Try to load the image from a pickle file if pickle has been successfully loaded |
| 47 | and from_pickle == True. |
| 48 | If failed, it will start the decoding procedure, after which it will store the |
| 49 | self.pixels into a pickle file (only self.pixels is stored) if to_pickle == True |
| 50 | ''' |
| 51 | if dir is None: |
| 52 | dir = Png.default_dir |
| 53 | # Decide whether to check crc |
| 54 | self.crc = crc |
| 55 | if crc == True and crc32_loaded == False: |
| 56 | self.crc = False |
| 57 | print("Cyclic Redundancy Check can not be implemented, for" + |
| 58 | "related function is not imported successfully.") |
| 59 | |
| 60 | # Work out the paths |
| 61 | filename = filename + ".png" if filename[-4:] != ".png" else filename |
| 62 | image_path = dir + filename |
| 63 | self.name = filename |
| 64 | self.path = image_path |
| 65 | if pickle_loaded: |
| 66 | pickle_path = f"{pickle_dir}{filename[:-4]}.pickle" |
| 67 | |
| 68 | # Pickle has been loaded and corresponding pickle file has been found |
| 69 | decoded = False |
| 70 | try: |
| 71 | if from_pickle: |
| 72 | with open(pickle_path, "rb") as image_pickle: |
| 73 | self.pixels = pickle.load(image_pickle) |
| 74 | # Only self.pixels is read, whereas self.width and self.height |
| 75 | # are necessary in self.__str__ and self.display |
| 76 | with open(image_path, "rb") as image: |
| 77 | self.bin:bytes = image.read() |
| 78 | self.get_image_properties() |
| 79 | if self.color_type == 3: |
| 80 | self.get_palette() |
| 81 | # Demanded in the arguement not to load from the pickle file that |
| 82 | # may exist |
| 83 | else: |
| 84 | self.decode(image_path) |
| 85 | decoded = True |
| 86 | # Pickle has been loaded while failing to find corresponding pickle file |
| 87 | except FileNotFoundError: |
| 88 | self.decode(image_path) |
| 89 | decoded = True |