问题描述
我使用 V8 编写了 nodejs 插件。我被困在我试图返回 Mat 的地方,但我得到的只是大小为 2mb 的损坏图像(对于特定图像)。难道我做错了什么?我如何使用 V8 做到这一点?
CPP 代码片段
cv::Mat image = ...
std::string my_cv_mat(image.begin<unsigned char>(),image.end<unsigned char>());
args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate,my_cv_mat.c_str()).ToLocalChecked());
Nodejs 代码片段
// body is express req.body
let bodyBuffer = new Buffer.from(body,"binary");
let detectedFaces = faceDetect.detect(bodyBuffer) //here I'm reading above Mat image into char string
const out_file = path.basename("output.png")
fs.writeFileSync(out_file,new Buffer.from(detectedFaces,"binary"))
--- 更新 ---
我已经更新了代码,但输出图像仍然不是图像,它的大小现在是 23mb 而应该是 700kb。
CPP 更新的代码片段
unsigned int img_size = image.total() * image.elemSize();
char* image_char = reinterpret_cast<char*>(image.data);
Nan::MaybeLocal<v8::Object> imageBuffer = Nan::copyBuffer(image_char,img_size);
// args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate,my_cv_mat.c_str()).ToLocalChecked());
args.GetReturnValue().Set(imageBuffer.ToLocalChecked());
nodejs 代码片段
let detectedFaces = faceDetect.detect(bodyBuffer)
const out_file = path.basename("output.png")
fs.writeFileSync(out_file,"binary"))
解决方法
我不认为 UTF-8 编码的字符串(或更准确地说:从原始图像数据构造 JavaScript 字符串,您告诉 String 构造函数将其视为 UTF-8 并相应地解码)是正确的工具为了这份工作。
尝试直接在您的插件中创建一个缓冲区,并将其作为调用结果(而不是 v8::String
)返回。