Francisco Presencia
Francisco Presencia

Reputation: 8860

Convert raw image to buffer

There is apparently no easy way to stream images in Raspberry Pi. While there are many hacks available, in my Raspberry Pi Zero it has some trouble keeping a decent framerate.

I suspect one of the main problems is that the 1st Google solution and most of them writes/reads to the SD for each image. I've got so far to read from the terminal an image without touching the SD:

const out = await exec(`fswebcam -r 640x480 -`);
const img = out[0];
console.log(img);

This gives me this on the terminal:

 ����JFIF``��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality
��      

 $.' ",#(7),01444'9=82<.342��C          

And many more. Previously I was doing something similar with buffers:

const file = fs.readFileSync(temp);
console.log(file.toString('base64'));
ctx.socket.emit('frame', { image: true, buffer: file.toString('base64') });

Where file is a Buffer and file.toString('base64') is a string in the form of:

/9j/4AAQSkZJRgABAQEAYABgAAD//gA8Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2ODApLCBxdWFsaXR5ID0gMTAwCv ...

And this worked (but through the SD card). So my question is, what is the format of the first output in terminal? And how can I convert it to a Buffer or a String similar to the latter.

Upvotes: 1

Views: 1818

Answers (1)

Francisco Presencia
Francisco Presencia

Reputation: 8860

I ended up just using the terminal through pipe to convert it to base64:

fswebcam -r 640x480 - | base64

So now my whole snippet is:

// Take a picture in an async way and return it as a base64 encoded string
// Props: https://scottlinux.com/2012/09/01/encode-or-decode-base64-from-the-command-line/
module.exports = async ({ resolution = '640x480', rotate = 0 } = {}) => {
  const query = `fswebcam -r ${resolution} --rotate ${rotate} - | base64`;
  const out = await exec(query, { maxBuffer: 1024 * 1024 });
  return out[0];
};

Upvotes: 1

Related Questions