Reputation:
I want to generate and serve an image of text.
At the moment I'm trying to use text2png
:
text2png('this string', {font: '14px Courier', bgColor: 'white'})
But text2png
doesn't seem to be able to do unicode/emoji.
It's turning 🔥 into and chinese characters, e.g. ä¸æ–‡, into
.
Is there a way I can render strings containing these kinds of characters into images?
text2png
was working perfectly in other respects.
Upvotes: 1
Views: 1736
Reputation:
text2png
can't do this at the moment.
It depends on node-canvas
, which in turn depends on cairo. Cairo's stable version as of writing this (1.14.12) doesn't seem to support emoji.
However, the development version of cairo (1.15.8) supports emoji.
Features and Enhancements
- Support colored emoji glyphs, stored as PNG images in OpenType fonts.
So maybe building and trying to force node-canvas
to use this later version of cairo would work out.
For now, I found this package wkhtmltox
. It turns HTML into images (or PDFs, but I won't use that).
Make sure you have the command-line tool wkhtmltoimage
installed as well. The node.js package wkhtmltox
depends on it for image-generation. (We don't care about wkhtmltopdf
).
Pop all your text into some external HTML document, ./content.html
:
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
Here's some ä¸æ–‡ letters!
</body>
</html>
Then to render this:
const fs = require('fs');
const wkhtmltox = require('wkhtmltox');
const converter = new wkhtmltox();
converter.image(fs.createReadStream('content.html'), { format: "png" })
.pipe(fs.createWriteStream('image.png'));
We're piping the PNG buffer here, you can also pipe to HTTP response objects (well, any writeable stream).
wkhtmltox
will render everything like a browser would, as far as I can tell (even supporting styles etc.), as long as you have the fonts installed.
So make sure you have a font with Chinese glyphs installed.
I haven't tested with emoji myself, but I assume it will work as long as you have the correct fonts.
Upvotes: 2