View file Remove image backgrounds/remove-bg/dark/assets/js/change-background-color.js

File size: 9.16Kb
"use strict";

// Element References
const ForegroundimageInput = document.getElementById('ForegroundimageInput');
const uploadImage = document.getElementById('uploadimage');
const backgroundTransparent = document.getElementById('backgroundtransparent');
const bgimagetabcontentdiv = document.getElementById('bgimagetabcontentdiv');
const downloadBtn = document.getElementById('downloadBtn');
const overlay = document.getElementById('overlay');
const selectableImages = document.querySelectorAll('.selectable');
const imageInput = document.getElementById('imageInput');
const imageCanvas = document.getElementById('imageCanvas');
const bgcolor = document.getElementById('bgcolor');
const innerimages = document.getElementById('innerimages');
const bgimagetabcontentdiv1 = document.getElementById('bgimagetabcontentdiv');

// Tooltip Initialization
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});

let currentProcessedImage = ''; // Store the path of the current processed image

// Function to handle the Foreground image upload and background removal
ForegroundimageInput.addEventListener('change', (event) => {
    const file = event.target.files[0];

    if (file) {
        const formData = new FormData();
        formData.append('image', file);

        // Show loader (overlay)
        overlay.style.display = 'flex';

        // Upload the image and call the background removal script
        fetch('change-background-color.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update the image source with the processed image
                uploadImage.src = data.imagePath;
                backgroundTransparent.src = data.imagePath;
                backgroundTransparent.classList.replace('p-relative', 'p2-relative');

                // Store the current processed image path
                currentProcessedImage = data.imagePath;

                // Enable download button
                downloadBtn.style.display = '';
            } else {
                console.error('Error:', data.message);
            }

            // Hide loader (overlay)
            overlay.style.display = 'none';
        })
        .catch(error => {
            console.error('Error:', error);
            // Hide loader (overlay)
            overlay.style.display = 'none';
        });
    }
});

// Function to handle background image change on selecting an image
selectableImages.forEach((image) => {
    image.addEventListener('click', () => {
        const selectedImage = image.getAttribute('data-image');
        const imagePath = 'input/' + selectedImage;

        // Add the custom-bg-image class to bgimagetabcontentdiv
        bgimagetabcontentdiv.classList.add('custom-bg-image');
        // Set the background image
        bgimagetabcontentdiv.style.backgroundImage = `url('${imagePath}')`;
    });
});

// Function to handle background image upload
imageInput.addEventListener('change', (event) => {
    const file = event.target.files[0];

    if (file) {
        const reader = new FileReader();

        reader.onload = function (e) {
            // Add the custom-bg-image class to bgimagetabcontentdiv
            bgimagetabcontentdiv.classList.add('custom-bg-image');
            // Set the background image to the uploaded image
            bgimagetabcontentdiv.style.backgroundImage = `url('${e.target.result}')`;
        };

        reader.readAsDataURL(file);
    }
});

// Download the combined image when the download button is clicked
// Download the combined image when the download button is clicked
downloadBtn.addEventListener('click', (event) => {
    event.preventDefault(); // Prevent default anchor behavior

    // Capture the background color
    const bgColor = window.getComputedStyle(bgimagetabcontentdiv).backgroundColor;

    // Capture the background image URL if present
    const bgImage = window.getComputedStyle(bgimagetabcontentdiv).backgroundImage;
    const hasBgImage = bgImage !== 'none'; // Check if there's a background image set
    let bgImageSrc = null;

    // Extract the background image URL if available
    if (hasBgImage) {
        // Extract the base64 image from the background-image style
        bgImageSrc = bgImage.slice(5, -2).replace(/"/g, ''); // Clean up URL from `url("...")`
    }

    // Load the foreground (processed) image
    const foregroundImage = new Image();
    foregroundImage.src = currentProcessedImage || backgroundTransparent.src; // Fallback to the displayed image

    foregroundImage.onload = () => {
        // Set canvas dimensions based on the image size
        const canvasWidth = foregroundImage.width;
        const canvasHeight = foregroundImage.height;
        imageCanvas.width = canvasWidth;
        imageCanvas.height = canvasHeight;

        const ctx = imageCanvas.getContext('2d');

        // If there's a background image (base64 or URL), draw it first
        if (hasBgImage) {
            const bgImageObj = new Image();
            bgImageObj.src = bgImageSrc;

            bgImageObj.onload = () => {
                // Draw the background image on the canvas
                ctx.drawImage(bgImageObj, 0, 0, canvasWidth, canvasHeight);

                // Draw the foreground image on top of the background
                ctx.drawImage(foregroundImage, 0, 0, canvasWidth, canvasHeight);

                // Convert the canvas content to a base64 image
                const finalImage = imageCanvas.toDataURL('image/png');

                // Send the image to the server for saving
                fetch('save_image.php', {
                    method: 'POST',
                    body: JSON.stringify({ image: finalImage }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Trigger download of the saved image
                        const link = document.createElement('a');
                        link.href = data.filePath; // Server-provided file path
                        link.download = 'combined-image.png'; // Default download name
                        link.click(); // Trigger download
                    } else {
                        console.error('Error saving image:', data.message);
                    }
                })
                .catch(error => console.error('Error:', error));
            };
        } else {
            // If no background image, fill canvas with the background color
            ctx.fillStyle = bgColor;
            ctx.fillRect(0, 0, canvasWidth, canvasHeight);

            // Draw the foreground image on top of the background color
            ctx.drawImage(foregroundImage, 0, 0, canvasWidth, canvasHeight);

            // Convert the canvas content to a base64 image
            const finalImage = imageCanvas.toDataURL('image/png');

            // Send the image to the server for saving
            fetch('save_image.php', {
                method: 'POST',
                body: JSON.stringify({ image: finalImage }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Trigger download of the saved image
                    const link = document.createElement('a');
                    link.href = data.filePath; // Server-provided file path
                    link.download = 'combined-image.png'; // Default download name
                    link.click(); // Trigger download
                } else {
                    console.error('Error saving image:', data.message);
                }
            })
            .catch(error => console.error('Error:', error));
        }
    };
});




// Function to remove the background image and set background color
function setMenuBackgroundColor(color) {
    // Remove the background image by clearing the backgroundImage property
    bgimagetabcontentdiv1.style.backgroundImage = 'none';
    // Set the background color
    bgimagetabcontentdiv1.style.backgroundColor = color;
}

// Event listeners for color selection
document.getElementById('primarycolor').addEventListener('click', () => {
    setMenuBackgroundColor('#fd7e14');
});

document.getElementById('secondarycolor').addEventListener('click', () => {
    setMenuBackgroundColor('#0cbc87');
});

document.getElementById('defaultcolor').addEventListener('click', () => {
    setMenuBackgroundColor('#fd7e14');
});

// Handle custom color input
document.getElementById('customcolor').addEventListener('input', (event) => {
    const customColor = event.target.value;
    setMenuBackgroundColor(customColor);
});