/** * Converts an image URL to a base64 data URL with white background made transparent */ export async function makeWhiteTransparent(imageUrl: string): Promise { return new Promise((resolve, reject) => { const img = new Image(); img.crossOrigin = 'anonymous'; img.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { reject(new Error('Failed to get canvas context')); return; } canvas.width = img.width; canvas.height = img.height; // Draw the image ctx.drawImage(img, 0, 0); // Get image data const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const data = imageData.data; // Define white threshold (adjust if needed) const whiteThreshold = 240; // RGB values above this are considered "white" // Make white pixels transparent for (let i = 0; i < data.length; i += 4) { const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; // Check if pixel is white-ish if (r > whiteThreshold && g > whiteThreshold && b > whiteThreshold) { // Calculate how "white" this pixel is (0-1) const whiteness = Math.min(r, g, b) / 255; // Make it transparent based on whiteness data[i + 3] = Math.floor((1 - whiteness) * 255); } } // Put the modified image data back ctx.putImageData(imageData, 0, 0); // Convert to base64 const base64 = canvas.toDataURL('image/png'); resolve(base64); }; img.onerror = () => { reject(new Error('Failed to load image')); }; img.src = imageUrl; }); } /** * Fetches an image from URL and converts it to base64 */ export async function imageUrlToBase64(imageUrl: string): Promise { return new Promise((resolve, reject) => { const img = new Image(); img.crossOrigin = 'anonymous'; img.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { reject(new Error('Failed to get canvas context')); return; } canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); const base64 = canvas.toDataURL('image/png'); resolve(base64); }; img.onerror = () => { reject(new Error('Failed to load image')); }; img.src = imageUrl; }); }