node根据文字生成图片
生活随笔
收集整理的這篇文章主要介紹了
node根据文字生成图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路:
文字轉svg,svg轉png
需要引入兩個依賴:
npm i text-to-svg 文字轉svg npm i svg2png svg轉png圖片文字轉svg:
const express = require('express'); const app = express(); const TextToSVG = require('text-to-svg'); const textToSVG = TextToSVG.loadSync('fonts/文泉驛微米黑.ttf');app.all("*",function(req,res,next){//設置允許跨域的域名,*代表允許任意域名跨域res.header("Access-Control-Allow-Origin","*");//允許的header類型res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Accept,Content-type");res.header("Access-Control-Allow-Credentials",true);//跨域允許的請求方式res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("Content-Type","application/json;charset=utf-8")if (req.method.toLowerCase() == 'options')res.sendStatus(200); //讓options嘗試請求快速結束elsenext(); });const attributes = {fill: 'red', stroke: 'black'}; const options = {x: 0, y: 0, fontSize: 72, anchor: 'top', attributes: attributes,};app.get('/test',(req,res)=>{const svg = textToSVG.getSVG('hello', options);res.send(svg); }) app.listen(8000);在前臺頁面當中使用ajax訪問請求
<script>//1.創建ajax對象var xhr = new XMLHttpRequest();//2.告訴ajax請求地址以及請求方式xhr.open('get','http://localhost:8000/test');//3.發送請求xhr.send();//4.獲取服務器端給與客戶端的響應數據xhr.onload = function(){console.log(xhr.responseText);//xhr.responseText返回值是Stringdocument.body.innerHTML=xhr.responseText;}
在前臺頁面加一個表單:
后臺接收數據:
app.get('/test',(req,res)=>{console.log(req.query.text);const svg = textToSVG.getSVG(req.query.text, options);res.send(svg); }) app.get('/test',(req,res)=>{const svg = textToSVG.getSVG(req.query.text, options);res.send(svg); })把svg類型的圖片轉為png類型的圖片:
安裝依賴:
npm i svg-to-img轉png用法:
const svg = textToSVG.getSVG('hello', options); (async () => {const image = await svgToImg.from(svg).toPng({path: "./text.png"});console.log(image); })();轉jpeg:
const svgToImg = require("svg-to-img");(async () => {await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toJpeg({path: "./example.jpeg"}); })();webp:
const svgToImg = require("svg-to-img");(async () => {const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toWebp({width: 300});console.log(image); })();base64-encoded png:
const svgToImg = require("svg-to-img");(async () => {const image = await svgToImg.from("<svg xmlns='http://www.w3.org/2000/svg'/>").toPng({encoding: "base64"});console.log(image); })();總結
以上是生活随笔為你收集整理的node根据文字生成图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Biperpedia: An Ontol
- 下一篇: css中引入新的字体文件