'Is there a way to convert numpy array to PNG/JPG... payload without saving it as a file?

Suppose there exists a numpy array, data. I am trying to do the equivalent of the following

cv2.imwrite(filename, data)
with open(filename, 'rb') as fp:
     data_compressed = filename.read()

without having to write to a file. Is there a way to convert numpy array to its equivalent PNG/JPG... representation without having to write to a file and read it as binary?



Solution 1:[1]

As Miki pointed out, imencode(...) is the solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Makketronix