这次给大家带来node操作文字生成图片,node操作文字生成图片的注意事项有哪些,下面就是实战案例,一起来看一下。
解决思路
文字转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多毫秒,感觉足够了,分享出来希望能给大家一个参照
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js的正则表达式应用
js中typeof和类型判断(附代码)
js怎样检测浏览器内的脚本
以上就是node操作文字生成图片的详细内容。