問題分析
需要将圖檔的numpy的array資料轉換為bytes,轉換之後的bytes資料要等價于open(file,"rb")。在使用numpy的tobytes(等價于tostring)方法發現得到的bytes資料并不等價于open(file,"rb")資料,需要對array資料進行相同的圖檔格式編碼之後,再使用tobytes才行。
代碼
import cv2
img_path = "img/test.jpg"
#打開圖檔檔案擷取二進制資料
with open(img_path,"rb") as f:
#讀取圖檔的二進制資料
bin_contents = f.read()
#使用opencv讀取圖檔
img = cv2.imread(img_path)
#将numpy的數組轉換為bytes
array_bytes = img.tobytes()#或者使用img.tostring()
#對數組的圖檔格式進行編碼
success,encoded_image = cv2.imencode(".jpg",img)
#将數組轉為bytes
img_bytes = encoded_image.tostring()