0

I have a fastapi service built, that can communicate with a client by encoding the requested information in a json dictionary passed in its responses.

My dictionary will encode the current timestamp, any error_message, and optional data. This structure is fixed.

{
  "timestamp": "...",
  "error_message": "",
  "data": {}
}

I now need to send responses with PIL image/s encoded in the data field, and would like to find an elegant way to do it. My current approach is to encode the image to a json-friendly format (image -> bytes encoding -> latin1 encoding), together with information about the image size and mode, in order have all the data required to load back the image on the receiving side. My approach is based on this stackoverflow post.

Sender image encoding:

{
  "data": image.tobytes().decode("latin1"),
  "size": image.size,
  "mode": image.mode,
}

Receiver image decoding:

Image.frombytes(
  image_dict["mode"],
  image_dict["size"],
  image_dict["data"].encode("latin1"),
)

Is there a more elegant way to encode images as a field of a json dictionary? Can I drop the size and mode entries in some way?

HitLuca
  • 812
  • 7
  • 26
  • One approach to avoid the `size` and `mode` fields would be to pickle the image based on https://stackoverflow.com/questions/55892362/sending-opencv-image-in-json – HitLuca Aug 31 '21 at 09:11

0 Answers0