node文字生成图片的示例代码
程序员文章站
2022-09-08 14:12:26
今天老板提了需求,要在服务端生成邀请卡,嗯…,简单的说就是把要这张:
变成差多这样的:
后端搞ruby的哥们搞了个html转图片,说转得太慢了,...
今天老板提了需求,要在服务端生成邀请卡,嗯…,简单的说就是把要这张:
变成差多这样的:
后端搞ruby的哥们搞了个html转图片,说转得太慢了,我就把这坑接下来了
所以睡前就倒腾了下,搞了个简单的实现
解决思路
文字转svg -> svg转png -> 合并图片
相关*
- images node.js 轻量级跨平台图像编解码库,不需要额外安装依赖
- text-to-svg 文字转svg
- svg2png svg转png图片
示例代码
'use strict'; const fs = require('fs'); const images = require('images'); const texttosvg = require('text-to-svg'); const svg2png = require("svg2png"); const promise = require('bluebird'); promise.promisifyall(fs); const texttosvg = texttosvg.loadsync('fonts/文泉驿微米黑.ttf'); const sourceimg = images('./i/webwxgetmsgimg.jpg'); const swidth = sourceimg.width(); const sheight = sourceimg.height(); const svg1 = texttosvg.getsvg('魏长青-人人讲app', { x: 0, y: 0, fontsize: 24, anchor: 'top', }); const svg2 = texttosvg.getsvg('邀请您参加', { x: 0, y: 0, fontsize: 16, anchor: 'top', }); const svg3 = texttosvg.getsvg('人人讲课程', { x: 0, y: 0, fontsize: 32, anchor: 'top', }); promise.coroutine(function* generateinvitationcard() { const targetimg1path = './i/1.png'; const targetimg2path = './i/2.png'; const targetimg3path = './i/3.png'; const targetimg4path = './i/qrcode.jpg'; const [buffer1, buffer2, buffer3] = yield promise.all([ svg2png(svg1), svg2png(svg2), svg2png(svg3), ]); yield promise.all([ fs.writefileasync(targetimg1path, buffer1), fs.writefileasync(targetimg2path, buffer2), fs.writefileasync(targetimg3path, buffer3), ]); const target1img = images(targetimg1path); const t1width = target1img.width(); const t1height = target1img.height(); const offsetx1 = (swidth - t1width) / 2; const offsety1 = 200; const target2img = images(targetimg2path); const t2width = target2img.width(); const t2height = target2img.height(); const offsetx2 = (swidth - t2width) / 2; const offsety2 = 240; const target3img = images(targetimg3path); const t3width = target3img.width(); const t3height = target3img.height(); const offsetx3 = (swidth - t3width) / 2; const offsety3 = 270; const target4img = images(targetimg4path); const t4width = target4img.width(); const t4height = target4img.height(); const offsetx4 = (swidth - t4width) / 2; const offsety4 = 400; images(sourceimg) .draw(target1img, offsetx1, offsety1) .draw(target2img, offsetx2, offsety2) .draw(target3img, offsetx3, offsety3) .draw(target4img, offsetx4, offsety4) .save('./i/card.png', { quality : 90 }); })().catch(e => console.error(e));
注意事项
text-to-svg需要中文字体的支持,不然中文会乱码
在我的破电脑上执行一次只花了500多毫秒,感觉足够了,分享出来希望能给大家一个参照
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。