user3310334
user3310334

Reputation:

Render image of text with special unicode?

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  enter image description here  and chinese characters, e.g. 中文, into  enter image description here.

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

Answers (1)

user3310334
user3310334

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

Related Questions