jsscheller / imagemagick-wasm

imagemagick compiled to WASM
Apache License 2.0
2 stars 2 forks source link

Example of text in browser? #4

Closed av01d closed 3 months ago

av01d commented 3 months ago

I am trying to draw some text on an image using imagemagick-wasm. I found an example in your tests directory, which does not work in a browser (I assume it does function in node).

callMain([ "-size", "100x100", "label:test", "out.jpg" ])

results in:

this.program: UnableToReadFont `helvetica' @ error/annotate.c/RenderFreetype/1538. 3 [magick.js:29:304](http://test.webgear.nl/js/magick.js)
uncaught exception: Object
callMain([ "-size", "100x100", "-font",  "/fonts/ShareTechMono-Regular.ttf", "label:test", "out.jpg" ])

results in

this.program: UnableToReadFont `/fonts/ShareTechMono-Regular.ttf' @ warning/annotate.c/RenderType/1005. [magick.js:29:304](http://test.webgear.nl/js/magick.js)
this.program: UnableToReadFont `/fonts/ShareTechMono-Regular.ttf' @ error/annotate.c/RenderFreetype/1538.

Could you provide a browser example for drawing text? Ideally one with the default helvetica font and one with a .ttf font. Thanks!

av01d commented 3 months ago

Never mind, got it. It only works with ttf-fonts you load by url. In the exampe below, I use helvetica.ttf. worker.js:

import createModule from "https://unpkg.com/@jspawn/imagemagick-wasm/magick.mjs";

(async () => { 
  const magick = await createModule({
    // Tell Emscripten where the WASM file is located.
    locateFile: () => "https://unpkg.com/@jspawn/imagemagick-wasm/magick.wasm",
  });

  // Use `FS.createLazyFile` to create a file which reads from a URL.
  magick.FS.createLazyFile('/', 'sample.jpg', 'sample.jpg', true, false);
  // Read the TTF font
  magick.FS.createLazyFile('/', 'helvetica.ttf', 'helvetica.ttf', true, false);

   magick.callMain([
      'sample.jpg',
      '-pointsize',
      '60',
      '-gravity',
      'center',
      '-font',
      'helvetica.ttf', // Must match filename used in createLazyFile call above
      '-annotate',
      '+0+0',
      'I love my mom',
      'out.png'
   ]);

  const pngBuf = magick.FS.readFile("out.png");
  const pngBlob = new Blob([pngBuf], { type: "image/png" });

  // Send to main for a preview.
  postMessage(pngBlob);
})();