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));關于node中怎么根據文字生成圖片問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。