Encode and decode images and videos with strings
Without the need of temp files
Encode media to string:
import uu
from io import BytesIO
def encode_media_to_string(media_file_path):
encoded_media_byte_array = BytesIO()
uu.encode(media_file_path, encoded_media_byte_array)
return encoded_media_byte_array.getvalue().decode("ascii")
Decode string to media:
def decode_string_to_media(value):
bytes_string = BytesIO(value.encode("ascii"))
bytes_media = BytesIO()
uu.decode(bytes_string, bytes_media)
return bytes_media
We can test if the encode/decode functions above work for the image below.
from PIL import Image
image_file_path = "data/2021-12-01-convert-media-to-string/dogs.jpg"
image = Image.open(image_file_path)
image
We are able to recover the same image by decoding the encoded image.
image_text = encode_media_to_string(image_file_path)
image_bytes = decode_string_to_media(image_text)
Image.open(image_bytes)
Now, we want to check if we can recover the video below.
from IPython.display import Video
video_file_path = "data/2021-12-01-convert-media-to-string/archery.mp4"
Video(video_file_path, embed=True)
Both the video and the audio are recovered when decoding the encoded video data.
video_text = encode_media_to_string(video_file_path)
video_bytes = decode_string_to_media(video_text)
Video(video_bytes.getvalue(), embed=True, mimetype="video/mp4")