您好,登錄后才能下訂單哦!
node中怎么根據(jù)文字生成圖片,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
解決思路
文字轉(zhuǎn)svg -> svg轉(zhuǎn)png -> 合并圖片
相關(guān)輪子
images Node.js 輕量級(jí)跨平臺(tái)圖像編解碼庫(kù),不需要額外安裝依賴
text-to-svg 文字轉(zhuǎn)svg
svg2png svg轉(zhuǎn)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('魏長(zhǎng)青-人人講App', { x: 0, y: 0, fontSize: 24, anchor: 'top', }); const svg2 = textToSVG.getSVG('邀請(qǐng)您參加', { 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));
關(guān)于node中怎么根據(jù)文字生成圖片問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。