justadudewhohacks/opencv4nodejs

Issue with .imdecode(..), .getData(..) and Buffers

sohaieb opened this issue · 1 comments

Hello,

i would like to get image data loaded by .imdecode(..) method and write that data into image file,

so i used this code:

let c = cv.imdecode(data); // "data" is a **Buffer** variable
const imageBuffer = c.getData();
const buff = Buffer.from(imageBuffer);
let path = `uploads/${new Date().getTime()}.jpg`;
fs.writeFileSync(path, buff );

The code above created the image file, but it is corrupted (it displayed "failed to load image data" in explorer)..

after some researches, i tried this one too:

let c = cv.imdecode(data); // data is a **Buffer** variable
const imageBuffer = c.getData();
let ut8 = new Uint8Array(imageBuffer);
for (let i=0; i<imageBuffer.length; i++) {
     ut8[i] = imageBuffer[i];
}
let path = `uploads/${new Date().getTime()}.jpg`;
fs.writeFileSync(path, ut8);

but it still the same issue, the created files are all corrupted.

Finally i used this code to create the image file:

let c = cv.imdecode(data); // data is a **Buffer** variable
let path = `uploads/${new Date().getTime()}.jpg`;
fs.writeFileSync(path, ut8);
cv.imwrite('uploads/img2.jpg', c); // instead of fs.writeFileSync(path, ut8);

the code above worked for me , but as you noticed i used the "c" variable which is a type of Mat , but when using buffer with writeFileSync(..) that does not work.

Important to mention:
when i used data (type Buffer) variable directly to the .writeFileSync(..) without wrapping it with opencv, it worked and the file was created without corruption, but by wrapping it with opencv (using .imdecode(..) then .getData(..)) it will be corrupted,

so is there an issue with that method ?

or is there any other method to get the right buffer data from Mat instance?

Thanks in advance.