我有一个Java程序,它将通过网络套接字传入的一些数据写入mongodb,如下所示:
MongoCollection<Document> documents = mongoDatabase.getCollection(collection);
Document document = new Document("Yams_id", imagePayload.getYamsId());
document.append("file_format", imagePayload.getImageFileFormat());
document.append("image_compression", imagePayload.getImageEncoding());
document.append("MIME", "image/png");
document.append("width_in_pixels", imagePayload.getWidthInPixels());
document.append("height_in_pixels", imagePayload.getHeightInPixels());
document.append("timestamp", imagePayload.getTimestamp());
document.append("data_array_size_in_bytes", imagePayload.getDataArraySizeInBytes());
Binary data = new Binary(imageData);
document.append("image_bytes", data);
documents.insertOne(document);
我想用python取回图像以进行图像处理:
import pymongo
from pymongo import MongoClient
import pprint
from bson.json_util import dumps
import json
import bson
from PIL import Image
import io
def get_bytes():
#connect to db
client = MongoClient('IP', 27017)
db = client.wams_image_db
collection = db.client_images_to_process
# extracting most recent document
doc = collection.find().sort([('timestamp',-1)]).limit(1)
json_data=dumps(doc)
data=json.loads(json_data)
#read JSON
width_in_pixels = timestamp=data[0]['width_in_pixels']
height_in_pixels = timestamp=data[0]['height_in_pixels']
mime =data[0]['MIME']
timestamp=data[0]['timestamp']
image_bytes_dict=data[0]['image_bytes'] #json dictionary type
print("width_in_pixels:"+str(width_in_pixels)+",height_in_pixels:"+str(height_in_pixels))
#save to file
image_bytes=json.dumps(image_bytes_dict).encode('utf-8')
#attempt - 1
newFile=open('out.png','wb')
newFileBytes =bytearray(image_bytes)
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
#attempt - 2
#image = Image.frombytes('RGBA', (width_in_pixels,height_in_pixels),image_bytes, 'raw')
#image.save('out.png')
get_bytes()
我的尝试#1正在使用
newFile=open('out.png','wb')
newFileBytes =bytearray(image_bytes)
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
文件已创建,但是当我尝试打开它时, Windows错误显示“看来我们不支持此文件格式”,也尝试了byteorder='little'
,但是它给出了相同的错误。 / strong>
尝试#2:
#image = Image.frombytes('RGBA', (width_in_pixels,height_in_pixels),image_bytes, 'raw')
#image.save('out.png')
错误:
提高ValueError(“图像数据不足”)
尝试#3
当我使用'PNG'或'JPEG'格式时:
image = Image.frombytes('RGBA', (width_in_pixels,height_in_pixels),image_bytes, 'JPEG')
image.save('out.png')
我收到此错误:
OSError:解码器JPEG不可用
OR
OSError:解码器PNG不可用
确保图像发送正确,因为“ noSQLBooster”实际上可以显示图像的预览。
因此,我如何从mongodb中的Binary类型重构图像字节并将其保存为文件?
谢谢