@shanto-kumar/image-to-text-convert
v2.0.2
Published
Extract text from images and format them nicely into paragraphs. Supports both English and Bengali.
Maintainers
Readme
📦 @shanto-kumar/image-to-text-convert
A powerful Node.js package to extract and beautify text from images using Tesseract.js. Supports both Bengali and English OCR with automatic text formatting.
📋 Features
- 🔍 Extract text from images (JPG, PNG, etc.)
- 🌏 Supports both English and Bengali text
- ✨ Automatic text formatting and cleanup
- 🔄 Promise-based API
- ⚡ Easy integration with Express, React, and Next.js
- 📱 Works with both file paths and buffers
- 📦 Pure ESM package (ES Modules)
🚀 Installation
npm install @shanto-kumar/image-to-text-convert⚙️ Important: ES Modules
This package is pure ESM. It uses ES Modules exclusively. Make sure your project has either:
"type": "module"in your package.json, or- Use the
.mjsextension for your files
{
"type": "module"
// ... rest of your package.json
}📘 Usage Guide
Basic Usage (Node.js)
// Using ES Modules (recommended)
import { imageToText } from '@shanto-kumar/image-to-text-convert';
// Example usage with async/await
async function extractText() {
try {
const text = await imageToText('your/image.jpg');
console.log('Extracted text:', text);
} catch (error) {
console.error('Error:', error);
}
}
extractText();Express.js Integration
- First, set up your Express project and install dependencies:
npm install express multer @shanto-kumar/image-to-text-convert- Create your Express server (make sure to use .mjs extension or set "type": "module"):
import express from 'express';
import multer from 'multer';
import { imageToText } from '@shanto-kumar/image-to-text-convert';
import { unlink } from 'fs/promises';
import cors from 'cors';
const app = express();
const upload = multer({ dest: 'uploads/' });
// Enable CORS if needed
app.use(cors());
// File upload endpoint
app.post('/api/extract-text', upload.single('image'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No image file uploaded' });
}
const text = await imageToText(req.file.path);
// Clean up: remove uploaded file
await unlink(req.file.path);
res.json({ text });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});React Integration
- Set up your React project (e.g., using Vite or Create React App)
- Install required packages:
npm install @shanto-kumar/image-to-text-convert axios- Create an image upload component:
import { useState } from 'react';
import axios from 'axios';
function ImageUploader() {
const [text, setText] = useState('');
const [loading, setLoading] = useState(false);
const handleUpload = async (event) => {
const file = event.target.files[0];
if (!file) return;
const formData = new FormData();
formData.append('image', file);
setLoading(true);
try {
const { data } = await axios.post('http://localhost:3000/api/extract-text', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
setText(data.text);
} catch (error) {
console.error('Error:', error.response?.data?.error || error.message);
alert('Failed to extract text');
} finally {
setLoading(false);
}
};
return (
<div>
<input
type="file"
accept="image/*"
onChange={handleUpload}
disabled={loading}
/>
{loading && <p>Processing image...</p>}
{text && (
<div>
<h3>Extracted Text:</h3>
<pre>{text}</pre>
</div>
)}
</div>
);
}
export default ImageUploader;Next.js Integration
- Set up your Next.js project and install dependencies:
npm install next @shanto-kumar/image-to-text-convert uuid axios- Create an API route (
app/api/extract-text/route.js):
import { NextResponse } from 'next/server';
import { imageToText } from '@shanto-kumar/image-to-text-convert';
import { writeFile, unlink } from 'fs/promises';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
export async function POST(req) {
try {
const formData = await req.formData();
const file = formData.get('image');
if (!file) {
return NextResponse.json(
{ error: 'No image uploaded' },
{ status: 400 }
);
}
// Create temporary file
const buffer = Buffer.from(await file.arrayBuffer());
const tempName = uuidv4() + path.extname(file.name);
const tempPath = path.join(process.cwd(), 'uploads', tempName);
// Save and process file
await writeFile(tempPath, buffer);
const text = await imageToText(tempPath);
await unlink(tempPath);
return NextResponse.json({ text });
} catch (error) {
return NextResponse.json(
{ error: error.message },
{ status: 500 }
);
}
}- Create a client component (
app/components/ImageUploader.js):
'use client';
import { useState } from 'react';
import axios from 'axios';
export default function ImageUploader() {
const [text, setText] = useState('');
const [loading, setLoading] = useState(false);
const handleUpload = async (event) => {
const file = event.target.files[0];
if (!file) return;
const formData = new FormData();
formData.append('image', file);
setLoading(true);
try {
const { data } = await axios.post('/api/extract-text', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
setText(data.text);
} catch (error) {
console.error('Error:', error.response?.data?.error || error.message);
alert('Failed to extract text');
} finally {
setLoading(false);
}
};
return (
<div>
<input
type="file"
accept="image/*"
onChange={handleUpload}
disabled={loading}
/>
{loading && <p>Processing image...</p>}
{text && (
<div>
<h3>Extracted Text:</h3>
<pre>{text}</pre>
</div>
)}
</div>
);
}📁 Project Structure
Make sure to create the following directory structure:
📦 your-project/
├── 📁 uploads/ # For temporary file storage
├── 📁 node_modules/
├── package.json # Must have "type": "module"
└── [your application files]⚠️ Important Notes
- Create an
uploadsdirectory in your project root - Ensure proper error handling in production
- Implement file size limits and type validation
- Consider implementing rate limiting for API routes
- Clean up temporary files after processing
- Make sure your project is configured for ES Modules
- Configure Axios defaults and interceptors for better error handling
🔧 API Reference
imageToText(input)
input: Path to image file or buffer- Returns: Promise
- Supported image formats: JPG, PNG, BMP, etc.
- Supported languages: English (eng) and Bengali (ben)
👨💻 Author
📄 License
MIT
