Casey Chu
Casey Chu

Reputation: 25463

Render RGBA to PNG in pure JavaScript?

Let's say I have a canvas element, and I need to turn the image on the canvas into a PNG or JPEG. Of course, I can simply use canvas.toDataURL, but the problem is that I need to do this a twenty times a second, and canvas.toDataURL is extremely slow -- so slow that the capturing process misses frames because the browser is busy converting to PNG.

My idea is to call context.getImageData(...), which evidently is much faster, and send the returned CanvasPixelArray to a Web Worker, which will then process the raw image data into a PNG or JPEG. The problem is that I can't access the native canvas.toDataURL from within the Web Worker, so instead, I'll need to resort to pure JavaScript. I tried searching for libraries intended for Node.js, but those are written in C++. Are there any libraries in pure JavaScript that will render raw image data into a PNG or JPEG?

Upvotes: 15

Views: 3366

Answers (3)

Casey Chu
Casey Chu

Reputation: 25463

I was able to write my own PNG encoder, which supports both RGB and palette depending on how many colors there are. It's intended to be run as a Web Worker. I've open-sourced it as usain-png.

Upvotes: 0

ephemient
ephemient

Reputation: 204668

There have been several JavaScript ports of libpng, including pnglets (very old), data:demo, and PNGlib.

The PNG spec itself is pretty straightforward – the most difficult part you may have is with implementing a simple PNG encoder yourself is getting ZLIB right (for which there are also many independent JavaScript implementations out there).

Upvotes: 9

Laurent Perrin
Laurent Perrin

Reputation: 14881

There's actually a C++ to JavaScript compiler called Emscripten.

Someone made a port of libpng, which you might want to check.

Upvotes: 0

Related Questions