writing text on image with npm node-canvas in custom language

你说的曾经没有我的故事 提交于 2021-02-20 03:39:40

问题


I am trying to write on image with hindi language. I am using node-canvas library. There is some problem with my output. Can someone help me ?

const { createCanvas, loadImage, registerFont} = require('canvas')
const canvas = createCanvas(400, 400)
const ctx = canvas.getContext('2d')

var str= "यह.  मिसिसिपी   है";
console.log(str);
loadImage('missisippi.jpg').then((image) => {
  console.log(image);
  ctx.drawImage(image, 0 , 0, 400, 400);
  ctx.fillText(str,100,40);
  var body = canvas.toDataURL(),
  base64Data = body.replace(/^data:image\/png;base64,/,""),
  binaryData = new Buffer(base64Data, 'base64').toString('binary');

    require("fs").writeFile("out.png", binaryData, "binary", function(err) {
      console.log(err); // writes out file without error, but it's not a valid image
    })

    // console.log('<img src="' + canvas.toDataURL() + '" />')
})

This is the output image . You can see that मिसिसिपी is grammatically wrong. (In case u are familiar with Hindi.

I have also tried the very same thing with npm-gm. in that too I faced same issue. Can someone help me out in this issue ?

How can I write text on image with custom font ?


回答1:


The following is working fine for me -

var fs = require('fs')
var path = require('path')
var Canvas = require('canvas')

function fontFile (name) {
  return path.join(__dirname, '/fonts/', name)
}

Canvas.registerFont(fontFile('ARBLI___0.ttf'), {family: 'ARBLI___0'})

var canvas = Canvas.createCanvas(7100, 3500)
var ctx = canvas.getContext('2d')

var Image = Canvas.Image;
var img = new Image();
img.src = 'input/DOIT_Art_Size.jpg';

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

ctx.fillStyle = 'white';
ctx.textAlign = 'center';

ctx.font = '150pt ARBLI___0'
ctx.fillText('यह मिसिसिपी है',3900, 1700)

canvas.createPNGStream().pipe(fs.createWriteStream(path.join(__dirname, 'output/font.png')))
canvas.createJPEGStream().pipe(fs.createWriteStream(path.join(__dirname, 'output/font.jpg')))

My node version is 6.11.2. Canvas module is 2.0.0-alpha.16. My input image dimension is 7100*3500 pixels.



来源:https://stackoverflow.com/questions/50704175/writing-text-on-image-with-npm-node-canvas-in-custom-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!