Please bookmark this page to avoid losing your image tool!

Image Face Cropping Tool For Automated Detection And Extraction

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
You can edit the below JavaScript code to customize the image tool.
async function processImage(originalImg, padding = 0.2) {
    /**
     * Dynamically loads a script and returns a promise that resolves when the script is loaded.
     * @param {string} url The URL of the script to load.
     * @returns {Promise<void>}
     */
    const loadScript = (url) => {
        return new Promise((resolve, reject) => {
            if (document.querySelector(`script[src="${url}"]`)) {
                resolve();
                return;
            }
            const script = document.createElement('script');
            script.src = url;
            script.onload = () => resolve();
            script.onerror = (err) => reject(new Error(`Failed to load script: ${url}`));
            document.head.appendChild(script);
        });
    };

    // Define URLs for the face-api library and its models
    const FACE_API_JS_URL = 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.12/dist/face-api.min.js';
    const FACE_API_MODELS_URL = 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.12/model/';

    try {
        // Step 1: Load the face-api.js library if it's not already available
        if (typeof faceapi === 'undefined') {
            await loadScript(FACE_API_JS_URL);
        }

        // Step 2: Load the required models if they haven't been loaded yet
        // We use a global flag to ensure models are only loaded once per session
        if (!window.faceApiModelsLoaded) {
            await faceapi.nets.tinyFaceDetector.loadFromUri(FACE_API_MODELS_URL);
            window.faceApiModelsLoaded = true;
        }

        // Step 3: Detect all faces in the image
        const detections = await faceapi.detectAllFaces(originalImg, new faceapi.TinyFaceDetectorOptions());

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        // Step 4: Handle the case where no faces are detected
        if (detections.length === 0) {
            canvas.width = originalImg.naturalWidth;
            canvas.height = originalImg.naturalHeight;
            ctx.drawImage(originalImg, 0, 0);
            
            // Add a "No faces detected" message on the image
            ctx.font = `bold ${Math.min(30, canvas.width / 10)}px Arial`;
            ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('No faces detected', canvas.width / 2, canvas.height / 2);
            
            return canvas;
        }

        // Step 5: Process each detected face
        const croppedBoxes = detections.map(detection => {
            const box = detection.box;
            // The padding value is a percentage of the detected face's width/height.
            // This padding is added to each side of the box.
            const padX = box.width * padding;
            const padY = box.height * padding;

            const sx = Math.max(0, box.x - padX);
            const sy = Math.max(0, box.y - padY);
            let sWidth = box.width + 2 * padX;
            let sHeight = box.height + 2 * padY;

            // Clamp the crop dimensions to ensure they are within the original image boundaries
            if (sx + sWidth > originalImg.naturalWidth) {
                sWidth = originalImg.naturalWidth - sx;
            }
            if (sy + sHeight > originalImg.naturalHeight) {
                sHeight = originalImg.naturalHeight - sy;
            }

            return { sx, sy, sWidth, sHeight };
        });

        // Step 6: Create a single output canvas to display all cropped faces vertically
        const maxWidth = Math.max(...croppedBoxes.map(b => b.sWidth));
        const totalHeight = croppedBoxes.reduce((sum, b) => sum + b.sHeight, 0);

        canvas.width = maxWidth;
        canvas.height = totalHeight;

        let currentY = 0;
        for (const box of croppedBoxes) {
            // Center the cropped image horizontally if its width is less than the max width
            const dx = (maxWidth - box.sWidth) / 2;
            
            ctx.drawImage(
                originalImg,
                box.sx, box.sy, box.sWidth, box.sHeight, // Source rectangle
                dx, currentY, box.sWidth, box.sHeight    // Destination rectangle
            );
            currentY += box.sHeight;
        }

        return canvas;

    } catch (error) {
        console.error("An error occurred during face cropping:", error);
        
        // Return an element indicating failure
        const errorDiv = document.createElement('div');
        errorDiv.style.padding = '20px';
        errorDiv.style.border = '2px solid red';
        errorDiv.style.backgroundColor = '#ffeeee';
        errorDiv.style.color = 'red';
        errorDiv.textContent = `An error occurred: ${error.message}. Check the console for details.`;
        return errorDiv;
    }
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

The Image Face Cropping Tool for Automated Detection and Extraction enables users to automatically detect and crop faces from images. This tool is useful for applications such as creating profile pictures, generating avatars, enhancing photo albums, or processing images for security and identification systems. Users can upload their images, and the tool will extract detected faces, providing an easy way to focus on specific individuals in photographs without manual selection.

Leave a Reply

Your email address will not be published. Required fields are marked *