{"id":569,"date":"2024-07-18T20:52:50","date_gmt":"2024-07-18T19:52:50","guid":{"rendered":"https:\/\/divbydev.com\/?page_id=569"},"modified":"2024-07-18T21:29:30","modified_gmt":"2024-07-18T20:29:30","slug":"basic-background-removal-tool","status":"publish","type":"page","link":"https:\/\/divbydev.com\/index.php\/projects-2\/basic-background-removal-tool\/","title":{"rendered":"Basic Background Removal Tool"},"content":{"rendered":"\n<p>The Background Remover allows you to effortlessly remove the background from your images. Simply upload an image, select the background color and threshold, and let the tool handle the rest. You can then save or copy the processed image.<\/p>\n\n\n\n<p><strong>Use Cases:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>E-commerce:<\/strong> Prepare product images by removing backgrounds for a cleaner and more professional look.<\/li>\n\n\n\n<li><strong>Social Media:<\/strong> Create standout posts by isolating subjects from their backgrounds for a unique visual impact.<\/li>\n\n\n\n<li><strong>Graphic Design:<\/strong> Easily remove backgrounds to integrate images into various design projects with seamless blending.<\/li>\n<\/ul>\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Improved Basic Background Removal Tool<\/title>\n    <style>\n        \/* Reset all styles for this container *\/\n        #background-removal-tool {\n            all: unset;\n            display: block;\n        }\n\n        \/* Reapply custom styles *\/\n        #background-removal-tool * {\n            all: revert;\n        }\n\n        \/* Apply custom styles *\/\n        #background-removal-tool body {\n            font-family: Arial, sans-serif;\n            display: flex;\n            justify-content: center;\n            align-items: center;\n            min-height: 100vh;\n            background-color: #f0f0f0;\n            margin: 0;\n            flex-direction: column;\n            padding: 20px;\n        }\n\n        .site-header .header-image {\n            display: flex;\n            justify-content: flex-start;\n            width: 100px;\n            max-width: 100%; \/* Ensure the logo scales properly *\/\n            height: 100px;\n        }\n\n        #background-removal-tool .container {\n            background-color: white;\n            padding: 20px;\n            border-radius: 8px;\n            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\n            text-align: center;\n            width: 100%;\n            max-width: 800px;\n            margin: 20px 0;\n        }\n\n        #background-removal-tool #dropArea {\n            border: 2px dashed #ccc;\n            border-radius: 8px;\n            padding: 10px;\n            cursor: pointer;\n            margin-bottom: 20px;\n            position: relative;\n            height: 100px;\n            max-width: 775px;\n        }\n\n        #background-removal-tool #dropArea.dragover {\n            background-color: #f0f0f0;\n        }\n\n        #background-removal-tool input[type=\"file\"] {\n            display: none;\n        }\n\n        #background-removal-tool button {\n            padding: 10px;\n            border: none;\n            border-radius: 4px;\n            background-color: lightgrey;\n            color: black;\n            cursor: pointer;\n            margin: 5px;\n        }\n\n        #background-removal-tool button:hover {\n            background-color: grey;\n        }\n\n        #background-removal-tool #selectFileBtn {\n            margin-top: 10px;\n            padding: 10px;\n        }\n\n        #background-removal-tool #canvas {\n            border: 1px solid #ccc;\n            margin-top: 20px;\n            max-width: 100%;\n        }\n\n        @media (max-width: 600px) {\n            #background-removal-tool .container {\n                padding: 10px;\n            }\n\n            #background-removal-tool button {\n                padding: 8px;\n                margin: 4px;\n            }\n\n            #background-removal-tool #selectFileBtn {\n                padding: 8px;\n            }\n        }\n\n        #background-removal-tool {\n            font-family: Arial, sans-serif;\n            max-width: 800px;\n            margin: 0 auto;\n            padding: 20px;\n        }\n        #background-removal-tool #dropArea {\n            border: 2px dashed #ccc;\n            border-radius: 20px;\n            width: 100%;\n            height: 100px; \/* Reduced height *\/\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            cursor: pointer;\n        }\n        #background-removal-tool #dropArea.highlight {\n            border-color: #000;\n        }\n        #background-removal-tool #imagePreview, #background-removal-tool #resultCanvas {\n            max-width: 100%;\n            max-height: 300px;\n            margin-top: 20px;\n        }\n        #background-removal-tool button {\n            margin-top: 10px;\n            padding: 10px 20px;\n            font-size: 16px;\n            cursor: pointer;\n        }\n        #background-removal-tool #fileInput {\n            display: none;\n        }\n        #background-removal-tool #loadingMessage {\n            display: none;\n            margin-top: 10px;\n            font-weight: bold;\n        }\n        #background-removal-tool #debugInfo {\n            margin-top: 10px;\n            font-family: monospace;\n            white-space: pre-wrap;\n        }\n    <\/style>\n<\/head>\n<body>\n    <div id=\"background-removal-tool\">\n        <div class=\"container\">\n            <div id=\"dropArea\">\n                <p>Drag &#038; drop an image here or click to select<\/p>\n            <\/div>\n            <input type=\"file\" id=\"fileInput\" accept=\"image\/*\">\n            <img id=\"imagePreview\" alt=\"Image preview\" style=\"display: none;\">\n            <canvas id=\"resultCanvas\" style=\"display: none;\"><\/canvas>\n            <div>\n                <label for=\"colorPicker\">Select background color: <\/label>\n                <input type=\"color\" id=\"colorPicker\" value=\"#ffffff\">\n            <\/div>\n            <div>\n                <label for=\"thresholdSlider\">Threshold: <\/label>\n                <input type=\"range\" id=\"thresholdSlider\" min=\"0\" max=\"100\" value=\"30\">\n                <span id=\"thresholdValue\">30<\/span>\n            <\/div>\n            <div id=\"loadingMessage\">Processing image&#8230; This may take a while depending on your device.<\/div>\n            <div>\n                <button id=\"removeBtn\" disabled>Remove Background<\/button>\n                <button id=\"clearFileBtn\" disabled>Clear File<\/button>\n                <button id=\"clearResultBtn\" disabled>Clear Result<\/button>\n                <button id=\"saveBtn\" disabled>Save Image<\/button>\n            <\/div>\n            <div id=\"debugInfo\"><\/div>\n        <\/div>\n    <\/div>\n    <script>\n        const dropArea = document.getElementById('dropArea');\n        const fileInput = document.getElementById('fileInput');\n        const imagePreview = document.getElementById('imagePreview');\n        const resultCanvas = document.getElementById('resultCanvas');\n        const removeBtn = document.getElementById('removeBtn');\n        const clearFileBtn = document.getElementById('clearFileBtn');\n        const clearResultBtn = document.getElementById('clearResultBtn');\n        const saveBtn = document.getElementById('saveBtn');\n        const loadingMessage = document.getElementById('loadingMessage');\n        const colorPicker = document.getElementById('colorPicker');\n        const thresholdSlider = document.getElementById('thresholdSlider');\n        const thresholdValue = document.getElementById('thresholdValue');\n        const debugInfo = document.getElementById('debugInfo');\n\n        let selectedFile = null;\n\n        \/\/ Drag and drop functionality\n        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {\n            dropArea.addEventListener(eventName, preventDefaults, false);\n        });\n\n        function preventDefaults(e) {\n            e.preventDefault();\n            e.stopPropagation();\n        }\n\n        ['dragenter', 'dragover'].forEach(eventName => {\n            dropArea.addEventListener(eventName, highlight, false);\n        });\n\n        ['dragleave', 'drop'].forEach(eventName => {\n            dropArea.addEventListener(eventName, unhighlight, false);\n        });\n\n        function highlight() {\n            dropArea.classList.add('highlight');\n        }\n\n        function unhighlight() {\n            dropArea.classList.remove('highlight');\n        }\n\n        dropArea.addEventListener('drop', handleDrop, false);\n\n        function handleDrop(e) {\n            const dt = e.dataTransfer;\n            const files = dt.files;\n            handleFiles(files);\n        }\n\n        \/\/ File selection\n        dropArea.addEventListener('click', () => fileInput.click());\n        fileInput.addEventListener('change', () => handleFiles(fileInput.files));\n\n        function handleFiles(files) {\n            if (files.length > 0) {\n                selectedFile = files[0];\n                displayImage(selectedFile);\n                updateButtonStates();\n            }\n        }\n\n        function displayImage(file) {\n            const reader = new FileReader();\n            reader.onload = (e) => {\n                imagePreview.src = e.target.result;\n                imagePreview.style.display = 'block';\n                resultCanvas.style.display = 'none';\n            };\n            reader.readAsDataURL(file);\n        }\n\n        \/\/ Button functionality\n        removeBtn.addEventListener('click', removeBackground);\n        clearFileBtn.addEventListener('click', clearFile);\n        clearResultBtn.addEventListener('click', clearResult);\n        saveBtn.addEventListener('click', saveImage);\n\n        thresholdSlider.addEventListener('input', () => {\n            thresholdValue.textContent = thresholdSlider.value;\n        });\n\n        function removeBackground() {\n            if (!selectedFile) return;\n\n            loadingMessage.style.display = 'block';\n            removeBtn.disabled = true;\n\n            const img = new Image();\n            img.onload = function() {\n                const canvas = document.createElement('canvas');\n                canvas.width = img.width;\n                canvas.height = img.height;\n                const ctx = canvas.getContext('2d');\n                ctx.drawImage(img, 0, 0, img.width, img.height);\n                \n                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n                const data = imageData.data;\n\n                \/\/ Get the selected background color\n                const bgColor = hexToRgb(colorPicker.value);\n\n                \/\/ Get the threshold value\n                const threshold = parseInt(thresholdSlider.value);\n\n                let pixelsChanged = 0;\n                const totalPixels = data.length \/ 4;\n\n                \/\/ Loop through all pixels\n                for (let i = 0; i < data.length; i += 4) {\n                    const r = data[i];\n                    const g = data[i + 1];\n                    const b = data[i + 2];\n\n                    \/\/ If the color is similar to the background color, make it transparent\n                    if (colorDistance(bgColor, {r, g, b}) < threshold) {\n                        data[i + 3] = 0; \/\/ Set alpha to 0\n                        pixelsChanged++;\n                    }\n                }\n\n                \/\/ Put the modified image data back to the canvas\n                ctx.putImageData(imageData, 0, 0);\n\n                \/\/ Display the result\n                resultCanvas.width = img.width;\n                resultCanvas.height = img.height;\n                const resultCtx = resultCanvas.getContext('2d');\n                resultCtx.drawImage(canvas, 0, 0);\n\n                resultCanvas.style.display = 'block';\n                imagePreview.style.display = 'none';\n                loadingMessage.style.display = 'none';\n                updateButtonStates();\n\n                \/\/ Display debug info\n                const percentChanged = (pixelsChanged \/ totalPixels * 100).toFixed(2);\n                debugInfo.textContent = `Pixels changed: ${pixelsChanged} out of ${totalPixels} (${percentChanged}%)`;\n            };\n            img.src = URL.createObjectURL(selectedFile);\n        }\n\n        function hexToRgb(hex) {\n            const result = \/^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$\/i.exec(hex);\n            return result ? {\n                r: parseInt(result[1], 16),\n                g: parseInt(result[2], 16),\n                b: parseInt(result[3], 16)\n            } : null;\n        }\n\n        function colorDistance(color1, color2) {\n            return Math.sqrt(\n                Math.pow(color1.r - color2.r, 2) +\n                Math.pow(color1.g - color2.g, 2) +\n                Math.pow(color1.b - color2.b, 2)\n            );\n        }\n\n        function clearFile() {\n            selectedFile = null;\n            imagePreview.style.display = 'none';\n            resultCanvas.style.display = 'none';\n            fileInput.value = '';\n            debugInfo.textContent = '';\n            updateButtonStates();\n        }\n\n        function clearResult() {\n            resultCanvas.style.display = 'none';\n            imagePreview.style.display = 'block';\n            thresholdSlider.value = 30;\n            thresholdValue.textContent = 30;\n            debugInfo.textContent = '';\n            updateButtonStates();\n        }\n\n        function saveImage() {\n            if (resultCanvas.style.display !== 'none') {\n                const link = document.createElement('a');\n                link.download = 'background_removed.png';\n                link.href = resultCanvas.toDataURL();\n                link.click();\n            }\n        }\n\n        function updateButtonStates() {\n            const fileSelected = !!selectedFile;\n            const resultAvailable = resultCanvas.style.display !== 'none';\n\n            removeBtn.disabled = !fileSelected || resultAvailable;\n            clearFileBtn.disabled = !fileSelected;\n            clearResultBtn.disabled = !resultAvailable;\n            saveBtn.disabled = !resultAvailable;\n        }\n    <\/script>\n<\/body>\n<\/html>\n","protected":false},"excerpt":{"rendered":"<p>The Background Remover allows you to effortlessly remove the background from your images. Simply upload an image, select the background color and threshold, and let the tool handle the rest. You can then save or copy the processed image. Use Cases: Improved Basic Background Removal Tool Drag &#038; drop an image here or click to &#8230; <a title=\"Basic Background Removal Tool\" class=\"read-more\" href=\"https:\/\/divbydev.com\/index.php\/projects-2\/basic-background-removal-tool\/\" aria-label=\"Read more about Basic Background Removal Tool\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":230,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-569","page","type-page","status-publish"],"_links":{"self":[{"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/pages\/569","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/comments?post=569"}],"version-history":[{"count":7,"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/pages\/569\/revisions"}],"predecessor-version":[{"id":583,"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/pages\/569\/revisions\/583"}],"up":[{"embeddable":true,"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/pages\/230"}],"wp:attachment":[{"href":"https:\/\/divbydev.com\/index.php\/wp-json\/wp\/v2\/media?parent=569"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}