UNPKG

is-image-blurry

Version:

A lightweight TypeScript library to detect if an image is blurry using Laplacian variance

50 lines 2.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Detects if an image is blurry using Laplacian variance analysis * @param dataUrl - Base64 data URL of the image * @param threshold - Blur detection threshold (default: 400, lower = more sensitive) * @returns Promise that resolves to true if image is blurry, false otherwise */ function isImageBlurry({ dataUrl, threshold = 400 }) { return new Promise((resolve) => { const img = new Image(); img.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) return resolve(false); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, img.width, img.height); const imageData = ctx.getImageData(0, 0, img.width, img.height); const pixels = imageData.data; const gray = []; // Convert to grayscale for (let i = 0; i < pixels.length; i += 4) { const avg = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3; gray.push(avg); } const laplacian = []; const width = img.width; const height = img.height; // Apply Laplacian filter for (let y = 1; y < height - 1; y++) { for (let x = 1; x < width - 1; x++) { const idx = y * width + x; const laplacianValue = -gray[idx - width - 1] - gray[idx - width] - gray[idx - width + 1] - gray[idx - 1] + 8 * gray[idx] - gray[idx + 1] - gray[idx + width - 1] - gray[idx + width] - gray[idx + width + 1]; laplacian.push(laplacianValue); } } // Calculate variance const mean = laplacian.reduce((sum, val) => sum + val, 0) / laplacian.length; const variance = laplacian.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / laplacian.length; resolve(variance < threshold); // Adjust threshold as needed }; img.src = dataUrl; }); } exports.default = isImageBlurry; //# sourceMappingURL=index.js.map