Please bookmark this page to avoid losing your image tool!

Photo Smile Adder

(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, smileIntensity = "50") {
    // Parameter parsing
    let intensity = parseFloat(smileIntensity);
    if (isNaN(intensity) || intensity < 0) intensity = 50;
    const I = intensity / 100; // Nominally 0.5 for default intensity

    // Initialize output canvas
    const canvas = document.createElement('canvas');
    const width = originalImg.naturalWidth || originalImg.width;
    const height = originalImg.naturalHeight || originalImg.height;
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');
    
    // Check for valid dimensions
    if (width === 0 || height === 0) {
        return canvas;
    }

    try {
        ctx.drawImage(originalImg, 0, 0, width, height);
    } catch (e) {
        console.error("Failed to draw image to canvas:", e);
        return canvas;
    }

    // Dynamic loading of face-api.js
    if (typeof window.faceapi === 'undefined') {
        if (!window.faceApiLoading) {
            window.faceApiLoading = new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api/dist/face-api.js';
                script.onload = resolve;
                script.onerror = () => reject(new Error('Failed to load face-api.js'));
                document.head.appendChild(script);
            });
        }
        try {
            await window.faceApiLoading;
        } catch (e) {
            console.error(e);
            return canvas;
        }
    }

    const faceapi = window.faceapi;

    // Load necessary face-api models
    if (!window.faceApiModelsLoaded) {
        const MODEL_URL = 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api/model/';
        window.faceApiModelsLoaded = Promise.all([
            faceapi.nets.ssdMobilenetv1.loadFromUri(MODEL_URL),
            faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL)
        ]);
    }

    try {
        await window.faceApiModelsLoaded;
    } catch (e) {
        console.error("Failed to load face-api models:", e);
        return canvas;
    }

    // Detect faces and landmarks
    let detections;
    try {
        detections = await faceapi.detectAllFaces(canvas).withFaceLandmarks();
    } catch (e) {
        console.error("Error during face detection. The image might be cross-origin tainted.", e);
        return canvas;
    }

    if (!detections || detections.length === 0) {
        console.warn("No faces detected in the image.");
        return canvas;
    }

    // Grab original image data
    let srcImageData;
    try {
        srcImageData = ctx.getImageData(0, 0, width, height);
    } catch (e) {
        console.error("Canvas tainted, cannot process pixels locally.", e);
        return canvas;
    }

    const dstImageData = ctx.createImageData(width, height);
    const srcData = srcImageData.data;
    const dstData = dstImageData.data;
    
    // Copy initially
    dstData.set(srcData);

    const warps = [];

    // Analyze faces to formulate displacement points for smiles
    for (const det of detections) {
        const p = det.landmarks.positions;
        
        // 68-point landmarks specific indices:
        // 48: left mouth corner, 54: right mouth corner, 57: bottom-center lip
        const p48 = p[48]; 
        const p54 = p[54];
        const p57 = p[57];

        const dx = p54.x - p48.x;
        const dy = p54.y - p48.y;
        const D = Math.sqrt(dx * dx + dy * dy); // Approximate width of mouth

        if (D === 0) continue;

        // Orthogonal unit vector pointing conceptually 'up' relative to the face
        const ux = dy / D;
        const uy = -dx / D;

        // Vector displacements: Pull corners outwards and upwards
        const pullOutwardAmt = 0.35;
        const pullUpwardAmt = 0.65;

        // Left corner movement
        const V48 = {
            x: D * I * ( (-dx / D) * pullOutwardAmt + ux * pullUpwardAmt ),
            y: D * I * ( (-dy / D) * pullOutwardAmt + uy * pullUpwardAmt )
        };

        // Right corner movement
        const V54 = {
            x: D * I * ( (dx / D) * pullOutwardAmt + ux * pullUpwardAmt ),
            y: D * I * ( (dy / D) * pullOutwardAmt + uy * pullUpwardAmt )
        };

        // Bottom lip slight depression stretch
        const V57 = {
            x: D * I * (-ux * 0.15),
            y: D * I * (-uy * 0.15)
        };

        // Cheeks plump up to form the smile "apples"
        const VCheekL = { x: V48.x * 0.6, y: V48.y * 0.6 };
        const pCheekL = { x: p48.x + ux * D * 0.45, y: p48.y + uy * D * 0.45 };
        
        const VCheekR = { x: V54.x * 0.6, y: V54.y * 0.6 };
        const pCheekR = { x: p54.x + ux * D * 0.45, y: p54.y + uy * D * 0.45 };

        // Append to localized warps map
        warps.push({ center: { x: p48.x + V48.x, y: p48.y + V48.y }, vector: V48, r: D * 0.85 });
        warps.push({ center: { x: p54.x + V54.x, y: p54.y + V54.y }, vector: V54, r: D * 0.85 });
        warps.push({ center: { x: p57.x + V57.x, y: p57.y + V57.y }, vector: V57, r: D * 0.6 });
        warps.push({ center: { x: pCheekL.x + VCheekL.x, y: pCheekL.y + VCheekL.y }, vector: VCheekL, r: D * 0.7 });
        warps.push({ center: { x: pCheekR.x + VCheekR.x, y: pCheekR.y + VCheekR.y }, vector: VCheekR, r: D * 0.7 });
    }

    if (warps.length === 0) return canvas;

    // Calculate maximum boundary of distorted pixels to optimize computation
    let minX = width, maxX = 0, minY = height, maxY = 0;
    for (const w of warps) {
        minX = Math.min(minX, w.center.x - w.r);
        maxX = Math.max(maxX, w.center.x + w.r);
        minY = Math.min(minY, w.center.y - w.r);
        maxY = Math.max(maxY, w.center.y + w.r);
    }

    minX = Math.max(0, Math.floor(minX));
    maxX = Math.min(width, Math.ceil(maxX));
    minY = Math.max(0, Math.floor(minY));
    maxY = Math.min(height, Math.ceil(maxY));

    const getIdx = (x, y) => (y * width + x) * 4;

    // Apply Inverse Distance Weighting Warp
    for (let y = minY; y < maxY; y++) {
        for (let x = minX; x < maxX; x++) {
            let dispX = 0, dispY = 0;
            let warped = false;

            for (const w of warps) {
                const dist = Math.sqrt((x - w.center.x) ** 2 + (y - w.center.y) ** 2);
                if (dist < w.r) {
                    const weight = Math.pow(1 - dist / w.r, 2); // Smoothly decay offset distance
                    dispX += w.vector.x * weight;
                    dispY += w.vector.y * weight;
                    warped = true;
                }
            }

            if (warped) {
                const srcX = x - dispX;
                const srcY = y - dispY;

                const xF = Math.floor(srcX);
                const yF = Math.floor(srcY);
                const xC = xF + 1;
                const yC = yF + 1;
                
                const xFrac = srcX - xF;
                const yFrac = srcY - yF;

                // Bilinear interpolation weights
                const w1 = (1 - xFrac) * (1 - yFrac);
                const w2 = xFrac * (1 - yFrac);
                const w3 = (1 - xFrac) * yFrac;
                const w4 = xFrac * yFrac;

                const cx0 = Math.max(0, Math.min(width - 1, xF));
                const cx1 = Math.max(0, Math.min(width - 1, xC));
                const cy0 = Math.max(0, Math.min(height - 1, yF));
                const cy1 = Math.max(0, Math.min(height - 1, yC));

                const i1 = getIdx(cx0, cy0);
                const i2 = getIdx(cx1, cy0);
                const i3 = getIdx(cx0, cy1);
                const i4 = getIdx(cx1, cy1);

                const outIdx = getIdx(x, y);

                for (let c = 0; c < 4; c++) {
                    dstData[outIdx + c] = 
                        srcData[i1 + c] * w1 + 
                        srcData[i2 + c] * w2 + 
                        srcData[i3 + c] * w3 + 
                        srcData[i4 + c] * w4;
                }
            }
        }
    }

    ctx.putImageData(dstImageData, 0, 0);

    return canvas;
}

Free Image Tool Creator

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

Description

The Photo Smile Adder is an image editing tool that uses facial recognition technology to add a smile to people in your photos. By detecting facial landmarks such as the mouth and cheeks, the tool can intelligently warp the image to simulate a natural-looking smile with adjustable intensity. This tool is useful for enhancing portraits, correcting expressions in group photos, or adding a touch of cheerfulness to casual snapshots.

Leave a Reply

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