Exemplo n.º 1
0
def encode_text(text_fp: str, img_fp: str, result_fp: str, key: str) -> str:
    """
    Main process for encoding text (UTF-8 encoded) from a file into
    an 8-bit, three-color image. Creates a SteganoImage() instance
    for managing the pixel data.

    Returns:
        A copy of the given image with the given message hidden
        within, at result_fp. If the text file is empty, returns
        the given image unaltered.
    """

    try:
        with Image.open(img_fp) as og_img:
            if og_img.size < (3, 3):
                print("Specified image is too small to be encoded onto.")
                return result_fp
    except (FileNotFoundError, UnidentifiedImageError):
        print("Specified image cannot be found or opened.")
    except Exception as e:
        print(e)

    if len(key) < 8:  # Additional key validation is needed
        print("Key must be at least 8 characters long, no spaces.")

    try:
        with open(text_fp, "r", -1, "utf-8") as text_file:

            img = SteganoImage(img_fp, key)
            ref_x = 0
            ref_y = 0

            buffer = text_file.read(1)
            while buffer != '':
                encode_to_cluster(buffer, ref_x, ref_y, img.pixelmap)
                img.occupied.add((ref_x, ref_y))
                ref_x, ref_y = find_next_open(ref_x, ref_y, img)
                buffer = text_file.read(1)

            encoded_img = Image.fromarray(img.pixelmap)
            encoded_img.save(result_fp)

            img.close_fp()  # Important to clean up open files

    except (OSError):
        print("Specified text file cannot be accessed.")

    return result_fp
Exemplo n.º 2
0
 def test_encode_cluster_04(self):
     char = FOUR_BYTE_CHAR
     expected = [0, 2, 3, 2, 0, 1, 3, 0, 0, 3, 3, 0, 0, 2, 1, 3, 2, 2]
     encode_to_cluster(char, 0, 1, self.pixelmap)
     result = [channel for y in range (0, 2) for x in range(0, 3) for channel in self.pixelmap[y, x]]
     self.assertEqual(expected, result)