[node] Recognize and extract text in pictures with the help of Baidu Smart Cloud

Renderings:

1. Connect with Baidu Smart Cloud

Log in to Baidu Smart Cloud: Baidu Smart Cloud-Integration of cloud and intelligence goes deep into the industry

New users can experience it for free, just follow the steps below:

 After creating the application, there will be a key or something

2. Install and use dependencies in the node project 

All dependencies are as follows:

    "baidu-aip-sdk": "^4.16.12",
    "express": "^4.18.2",
    "multer": "^1.4.5-lts.1",
    "nodemon": "^2.0.22"

If you don’t know the installation command, you can find it here: npm

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>图片上传</title>
</head>

<body>
    <form id="uploadForm">
        <input type="file" id="fileInput">
        <button type="submit">上传图片</button>
    </form>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#uploadForm').submit(function (event) {
                event.preventDefault(); // 阻止表单的默认提交行为

                const formData = new FormData();
                formData.append('image', $('#fileInput')[0].files[0]);

                $.ajax({
                    url: 'http://127.0.0.1:3000/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (result) {
                        console.log(result);
                    },
                    error: function (error) {
                        console.error(error);
                    }
                });
            });
        });
    </script>
</body>

</html>

app.js, you need to create a static storage image in the same directory as app.js

var AipOcrClient = require("baidu-aip-sdk").ocr;
const express = require('express')
const multer = require('multer')
const fs = require('fs');
const path = require('path')
const app = express()

// 设置APPID/AK/SK
var APP_ID = "xxxxxxx";
var API_KEY = "xxxxxxxxxxxxxxxxxxxx";
var SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxx";
// 新建一个对象,建议只保存一个对象调用服务接口
var client = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY);

// diskStorage创建上传存储器 
const storage = multer.diskStorage({
    // 设置上传文件存储目录
    destination: function (req, file, cb) {
        cb(null, './static/')
    },
    //保存在 uploads 中的文件名
    filename: function (req, file, cb) {
        const extname = path.extname(file.originalname) // 获取文件后缀名
        const filename = Date.now() + '' + extname     // 时间戳+后缀名 生成唯一文件名
        cb(null, filename)
    }
})

//创建一个名为upload的文件上传示例
const upload = multer({ storage: storage })

// 创建上传路由
// upload.single('image') 处理单个文件上传
app.post('/upload', upload.single('image'), (req, res) => {
    const file = req.file
    if (!file) {
        return res.status(400).send('请选择要上传的图片')
    }
    const filePath = req.file.path;
    // 读取文件
    fs.readFile(filePath, (err, data) => {
        if (err) {
            console.error(err);
            res.status(500).send('Failed to read the file.');
            return;
        }
        // 将文件数据转换为 Base64
        const base64Data = data.toString('base64');
        client.generalBasic(base64Data).then(function(result) {
            res.send(result)
            console.log(result);
        }).catch(function(err) {
            console.log(err);
        });
    });
})


const PORT = process.env.PORT || 3000;
// 启动服务器
app.listen(3000, () => {
    console.log(`Server running on http://localhost:${PORT}`)
})

annotation:

Baidu Smart Cloud can see more detailed documents: Interface Description - Text Recognition OCR

Guess you like

Origin blog.csdn.net/weixin_52479803/article/details/131589765