ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

干饭人表情包使用nodejs实现

2021-03-15 10:03:14  阅读:215  来源: 互联网

标签:const nodejs require express images 干饭 txt app 表情


7772410fa460ad7fe2b9b31064ddb084.jpeg 很流行的一款表情包效果举牌人,这次也用nodejs实现一把。 7728b839b2008d5a115fe0a00d1bd9f8.jpeg需要的插件

  • text-to-svg 把文字转换为svg

text-to-svggithub.com

const TextToSVG = require("text-to-svg"); const textToSVG = TextToSVG.loadSync("./fonts/msyh.ttf"); // 加载字体文件 const svg1 = textToSVG.getSVG('这是一段文字', {  x: 0,  y: 0,  fontSize: 20,  anchor: "top", }); // 把文字转换为svg
  • svg2png 把svg转换为png图片

domenic/svg2pnggithub.com图标

const fs = require('fs'); const svg2png = require("svg2png"); // 把svg保存成图片 svg2png(Buffer.from(svg1), {}).then(buffer=>fs.writeFile("./dest.png", buffer));
  • images 此插件的作用主要是对图片进行拼接组合

zhangyuanwei/node-imagesgithub.com图标

var images = require("images");  images("input.jpg")                     //Load image from file   //加载图像文件   .size(400)                          //Geometric scaling the image to 400 pixels width  //等比缩放图像到400像素宽     .draw(images("logo.png"), 10, 10)   //Drawn logo at coordinates (10,10)  //在(10,10)处绘制Logo     .save("output.jpg", {               //Save the image to a file, with the quality of 50  quality : 50 //保存图片到文件,图片质量为50     });

通过以上三个插件的结合就可以实现效果。

安装

npm init -y npm i text-to-svg svg2png images express # 安装插件,安装express的目的是做一个web页面作为入口进行展示

实现

目录结构如下

fonts images public utils app.js

utils/tools.js

const images = require("images"); const TextToSVG = require("text-to-svg"); const svg2png = require("svg2png"); const textToSVG = TextToSVG.loadSync("./fonts/msyh.ttf");  /**  * 根据文字生成图片  * @param txt   需要生成的文字  * @param cb    生成之后的回调函数  */ function initImg(txt, cb) {   txt = txt.trim();   let w = Math.max(...txt.split("\n").map((item) => item.length)) * 80; // 计算宽度,换行分割之后取最大宽度作为图片最终的宽度   let h = txt.split("\n").length * 164; // 计算高度,换行分割后的行数*每一行的高度    // 每一个文字进行分割生成svg图片     const txtPromise = txt.split("").map((item) => {     const svg1 = textToSVG.getSVG(item, {       x: 0,       y: 0,       fontSize: 20,       anchor: "top",     });     return svg2png(Buffer.from(svg1), {});   });   // 所有生成png的Promise对象放在一个Promise.all数组中,等所有的svg都生成之后把结果一起进行绘制   Promise.all(txtPromise).then((txtImgs) => {     const result = images(w, h); // 最终绘制的结果     let xIndex = 0;     let yIndex = 0;     txtImgs.forEach((p, index) => {       if (txt.split("")[index] == "\n") {         yIndex += 1;         xIndex = 0;       } else {         result.draw(           images(             `./images/QP4a5rvW_${Math.floor(Math.random() * 40)}.png`           ).draw(images(p).rotate(35), 22, 8),           xIndex * 80,           yIndex * 164         );         xIndex += 1;       }     });     const fileName = Math.random() + ".png";     result.save(`./public/${fileName}`);     cb(fileName);   }); }  module.exports = {   initImg, };

app.js

const express = require("express"); const { initImg } = require("./utils/tools"); const app = express(); app.use(   express.urlencoded({     extended: false,   }) ); app.use(express.json()); app.use(express.static("./public"));  app.post("/api/v1/jpr", (req, res) => {   console.log(req.body);   initImg(req.body.content, (filename) => {     res.json({       code: 1,       info: "/" + filename,     });   }); });

public/index.html

<!DOCTYPE html> <html>   <head>     <meta charset="UTF-8" />     <meta name="viewport" content="width=device-width, initial-scale=1.0" />     <title>举牌人</title>     <link       rel="stylesheet"       href="https://cdn.jsdelivr.net/npm/tailwindcss@2.0.2/dist/tailwind.min.css"     />   </head>   <body class="container flex flex-col justify-center items-center">     <img src="" id="img" alt="" class="w-1/2" />     <textarea       type="text"       class="w-1/2 px-4 py-2 m-2 border border-gray-300"       placeholder="请输入举牌文字"       id="txt"     ></textarea>      <button       onclick="saveHandle()"       class="bg-red-600 text-red-100 font-bold px-4 py-2 m-2 w-1/3"     >       生成     </button>     <script>       function saveHandle() {         console.log(document.getElementById("txt").value);         fetch("/api/v1/jpr", {           method: "POST",           body: JSON.stringify({             content: document.getElementById("txt").value,           }),           headers: {             "Content-Type": "application/json",           },         })           .then((res) => res.json())           .then((data) => {             document.getElementById("img").src = data.info;           });       }     </script>   </body> </html>

运行

node app.js # 在浏览器中访问 http://localhost:3000

原文来自千锋教育,转载请注明出处。

标签:const,nodejs,require,express,images,干饭,txt,app,表情
来源: https://blog.51cto.com/15128693/2659841

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有