2.0.2 ⢠Published 3 months ago
@shanto-kumar/image-to-text-convert v2.0.2
š¦ @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
.mjs
extension 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
uploads
directory 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