I am receiving an image as bytes that I would like to store using specifically with open command due to library restrictions. Therefore I am unable to use libs like opencv2 and PIL
mport numpy as np
import base64
import cv2
import io
from os.path import dirname, join
from com.chaquo.python import Python
def main(data):
decoded_data = base64.b64decode(data)
files_dir = str(Python.getPlatform().getApplication().getFilesDir())
filename = join(dirname(files_dir), 'image.PNG')
with open(filename, 'rb') as file:
img = file.write(img)
return img
What I would simply like to do is save the image file to the current directory that i am in. Currently when i try my code it gives me the following error:
com.chaquo.python.PyException: TypeError: write() argument must be str, not bytes
Which requires me to have a string. I'd like to know what do i need to do to save the image as a .PNG file to the directory
CodePudding user response:
Try :
out_file = open(filename, 'wb')
out_file.write(decoded_data)
CodePudding user response:
For Conversion between base64 and OpenCV or PIL Image, please see the below example
https://jdhao.github.io/2020/03/17/base64_opencv_pil_image_conversion/
import base64
import numpy as np
import cv2
with open("test.jpg", "rb") as f:
im_b64 = base64.b64encode(f.read())
im_bytes = base64.b64decode(im_b64)
im_arr = np.frombuffer(im_bytes, dtype=np.uint8)
img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR)
cv2.imwrite(filename, img)