I need to encode image into binary, send it to server and decode it back to image again. The decoding method is:
def decode_from_bin(bin_data):
bin_data = base64.b64decode(bin_data)
image = np.asarray(bytearray(bin_data), dtype=np.uint8)
img = cv2.imdecode(image, cv2.IMREAD_COLOR)
return img
We use OpenCV to encode image:
def encode_from_cv2(img_name):
img = cv2.imread(img_name, cv2.IMREAD_COLOR) # adjust with EXIF
bin = cv2.imencode('.jpg', img)[1]
return str(base64.b64encode(bin))[2:-1] # Raise error if I remove [2:-1]
You can run with:
raw_img_name = ${SOME_IMG_NAME}
encode_image = encode_from_cv2(raw_img_name)
decode_image = decode_from_bin(encode_image)
cv2.imshow('Decode', decode_image)
cv2.waitKey(0)
My question is: why do we have to strip the first two characters from base64 encoding?