I am trying to move my Base64
images to Buffers
made available in Socket.io 1.0
I load images with FileReader()
and resize them with the Canvas
element.
Canvas
has a still pretty unsupported .toBlob()
, anybody has a more compatible way of sending my canvas / image as a arraybuffer
over the socket which will also let me open buffer on the other side and make it a canvas / image again.
You can use canvas.toDataURL and send that base64 encoded dataURL using socketIO.
var theDataURL = canvas.toDataURL();
The dataURL is a .PNG representation of the image. You can also specify a .JPEG representation if you need a smaller file size canvas.
// quality ranges from 0.00-1.00
var jpgQuality=0.60;
// get the dataURL in .jpg format
var theDataURL = canvas.toDataURL('image/jpeg',jpgQuality);
Both the .png and .jpg dataURL formats are more lightweight than transporting the pixel array from context.getImageData
. The pixel array weighs in at canvas.width*canvas.height*4 while the .png and .jpg formats are compressed/optimized during encoding.
Base64 encoding results in a string so it's compatible with all browsers and all fallback versions of socketIO transport.
Then you can easily deserialize the dataURL on the receiving side like this:
var img=new Image();
img.onload=start;
img.src=theBase64URL;
function start(){
document.body.appendChild(img);
// or
context.drawImage(img,0,0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With