Пример #1
0
def decode(file_to_decode_path, out_file_path):
    """
    Decode file and write decoded data to out_file_path
    :param file_to_decode_path: obviously
    :param out_file_path: obviously
    """
    bmp_data = read_bytearray_from_file(file_to_decode_path)

    file_header = try_get_file_header(bmp_data)

    bmp_data = split_bytearray(bmp_data, file_header.off_bits)[1]

    msg = b'encoded'
    try:
        check_encoded(bmp_data, msg)
    except NotEncodedError:
        print("This file doesn't encoded. I can do nothing. Sorry...")
        exit(3)

    bmp_data = bmp_data[len(msg) * 8:]

    bits_for_file_length = 32
    file_length_data, bmp_data = split_bytearray(bmp_data, bits_for_file_length)

    file_length = _decode_specified_bits(file_length_data, 1,
                                         bits_for_file_length)

    bit_count_data, bmp_data = split_bytearray(bmp_data, 3)

    bit_count = _decode_specified_bits(bit_count_data, 1, 3) + 1

    file_data = _decode(bmp_data, bit_count, file_length)

    write_to(out_file_path, file_data)
Пример #2
0
def encode(bmp_file_path, file_to_encode_path, out_file_path, bit_count=1):
    """
    Encode something file to BMP file and record result to out_file_path
    :param bmp_file_path: BMP file
    :param file_to_encode_path: File to encode
    :param out_file_path: Obviously
    :param bit_count: bits per byte
    """
    bmp_data = read_bytearray_from_file(bmp_file_path)
    file_data = read_bytearray_from_file(file_to_encode_path)

    file_header = try_get_file_header(bmp_data)

    bits_for_file_length = 32

    header, bmp_data = split_bytearray(bmp_data, file_header.off_bits)

    msg = b"encoded"
    _encode(bytearray(msg), bmp_data, 1, 8)
    encoded_msg, bmp_data = split_bytearray(bmp_data, len(msg) * 8)

    file_length = len(file_data)
    _encode((file_length,), bmp_data, 1, bits_for_file_length)
    encoded_file_length, bmp_data = split_bytearray(bmp_data, bits_for_file_length)

    _encode((bit_count - 1,), bmp_data, 1, 3)
    encoded_bit_count, bmp_data = split_bytearray(bmp_data, 3)

    try:
        check_data_lost_possibility(file_data, bmp_data, bit_count)
    except DataLostPossibility:
        print("Your file too large for this bmp and bit count")
        exit(4)

    _encode(file_data, bmp_data, bit_count, 8)

    header.extend(encoded_msg)
    header.extend(encoded_file_length)
    header.extend(encoded_bit_count)
    header.extend(bmp_data)

    write_to(out_file_path, header)