一、NodeCanvas暂停
NodeCanvas是一个基于node.js的canvas库,可以使用JavaScript生成图形,支持多种绘图操作,像素操作,图像滤镜,字体处理,图像剪裁,图像合成,PDF输出等等功能。NodeCanvas提供了一种灵活的方式将canvas应用于服务器端。
然而,由于NodeCanvas是一个基于C++实现的插件,会存在部分API产生内存泄漏等问题。目前,NodeCanvas已经停止继续开发了。但是,有些互联网公司出于自身业务问题,仍在使用NodeCanvas。 而开发者们仍可以自行按照NodeCanvas实现原理,学习学习底层实现的方法。
二、NodeCanvasAPI
NodeCanvas提供了一套基本的API来操作canvas。这些API大部分类 态都是直接使用纯JavaScript调用,极其灵活。如果你曾经使用过前端 HTML5中的canvas,那么使用NodeCanvas去写服务器端 绘图代码将会变得非常简单。
以下是一些NodeCanvas常用的API:
// 创建一个新的canvas对象 const { createCanvas } = require('canvas'); const canvas = createCanvas(200, 200); // 通过绘制矩形来填充一个区域的颜色 const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, 100, 200); // 向canvas中渲染text ctx.font = '30px Impact'; ctx.rotate(0.1); ctx.fillText('Hello World!', 50, 100); // 创建一个png编码的Buffer,将图像写入到文件中的方法 const fs = require('fs'); const out = fs.createWriteStream(__dirname + '/text.png'); const stream = canvas.createPNGStream(); stream.pipe(out); out.on('finish', () => console.log('The PNG file was created.'));
三、NodeCanvas实战案例
1. 生成二维码图片
使用NodeCanvas,可以很容易地生成二维码图片。
const { createCanvas } = require('canvas'); const QRCode = require('qrcode'); const canvas = createCanvas(200, 200); const ctx = canvas.getContext('2d'); QRCode.toCanvas(canvas, 'https://www.example.com', (error) => { if (error) { console.error(error) return } console.log('success!'); }); console.log('');
2. 智能图像识别
使用NodeCanvas可以使用机器学习 AI技术,帮助我们实现智能图像识别功能。下面通过一个实例代码来了解这个过程:
// 使用tensorflow.js库来对图像进行classification const sharp = require('sharp'); const tf = require('@tensorflow/tfjs'); const { createCanvas, Image } = require('canvas'); // 将图像加载到一个ImageData对象中 sharp('image.jpg') .resize(224, 224) .toBuffer() .then(data => { const img = new Image(); img.onload = async () => { // 将图像转换为Tensor并进行预测 const tensor = tf.browser.fromPixels(img).expandDims(); const predictions = await model.predict(tensor).data(); // 按照顺序选择最大预测概率 const classes = ['cat', 'dog', 'bird']; const res = Array.from(predictions) .map((p, i) => ({ probability: p, className: classes[i] })) .sort((a, b) => b.probability - a.probability) .slice(0, 2); console.log(res); // 输出最大概率的两个类别 }; img.onerror = err => { throw err; }; img.src = data; });
3. 手写数字识别
// 使用TensorFlow.js进行手写数字识别 const fs = require('fs'); const { createCanvas, Image } = require('canvas'); const tf = require('@tensorflow/tfjs'); (async () => { const model = await tf.loadLayersModel('file://path/to/model.json'); const canvas = createCanvas(28, 28); const input = tf.browser.fromPixels(canvas).reshape([784]); // 绘制手写数字 const ctx = canvas.getContext('2d'); ctx.strokeStyle = '#fff'; ctx.lineWidth = 3; ctx.strokeRect(0, 0, 28, 28); ctx.lineWidth = 1; const _onmousedown = (e) => { ctx.beginPath(); ctx.moveTo(e.offsetX, e.offsetY); canvas.addEventListener('mousemove', _onmousemove); }; const _onmousemove = (e) => { ctx.lineTo(e.offsetX, e.offsetY); ctx.stroke(); }; const _onmouseup = (e) => { canvas.removeEventListener('mousemove', _onmousemove); // 将手写数字转换为Tensor并进行预测 const input = tf.browser.fromPixels(canvas).reshape([784]); const output = model.predict(input.expandDims(0)); const prediction = Array.from(await output.data()); console.log(prediction.indexOf(Math.max(...prediction))); // 输出预测结果 }; canvas.addEventListener('mousedown', _onmousedown); canvas.addEventListener('mouseup', _onmouseup); })();
总结
NodeCanvas虽然已经停息维护,但是,对于有其他业务需求的开发者来说,使用NodeCanvas仍是一个不错的选择。只要我们按照其API进行操作,就可以轻松地实现服务器端的图像处理,甚至是AI其他相关功能。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/186686.html