如何对Base64图像取反?求jsPDF场景下无法用getImageData的解决方案
Solution for Inverting Base64 Images for jsPDF
Since you can't directly invert Base64 image data and need to work within jsPDF's Base64-focused workflow, we'll build a full pipeline to convert Base64 to pixel data, invert the colors, then convert back to Base64. Here's a practical, step-by-step implementation:
Step 1: Convert Base64 to an Image Object (Async)
First, we need to load the Base64 string into an Image element. Image loading is asynchronous, so we'll use a Promise to handle this reliably:
function base64ToImage(base64String) { return new Promise((resolve, reject) => { const img = new Image(); // Enable cross-origin support if your Base64 comes from an external source img.crossOrigin = "anonymous"; img.onload = () => resolve(img); img.onerror = (err) => reject(err); img.src = base64String; }); }
Step 2: Invert Pixels & Convert Back to Base64
Next, we'll draw the image to an offscreen canvas, manipulate the pixel data to invert colors, then export the modified canvas back to Base64:
async function invertBase64Image(base64String) { try { const img = await base64ToImage(base64String); // Create a hidden canvas matching the image's dimensions const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; // Draw the original image onto the canvas ctx.drawImage(img, 0, 0); // Extract pixel data and invert colors const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const pixelData = imageData.data; // Iterate over each pixel: invert RGB channels, keep alpha intact for (let i = 0; i < pixelData.length; i += 4) { pixelData[i] = 255 - pixelData[i]; // Red channel inversion pixelData[i + 1] = 255 - pixelData[i + 1]; // Green channel inversion pixelData[i + 2] = 255 - pixelData[i + 2]; // Blue channel inversion // Leave alpha (pixelData[i+3]) unchanged to preserve transparency } // Apply the inverted pixel data back to the canvas ctx.putImageData(imageData, 0, 0); // Convert canvas back to Base64 (use "image/png" for lossless if needed) return canvas.toDataURL("image/jpeg", 0.5); } catch (err) { console.error("Failed to invert image:", err); throw err; } }
Step 3: Use the Inverted Base64 with jsPDF
Finally, integrate the inverted image into your jsPDF workflow:
// Example: Generate PDF with inverted image async function createPDF() { // Your original Base64 image (from canvas.toDataURL or elsewhere) const originalBase64 = canvas.toDataURL("image/jpeg", 0.5); // Get the inverted Base64 string const invertedBase64 = await invertBase64Image(originalBase64); // Initialize jsPDF and add the inverted image const doc = new jsPDF(); doc.addImage(invertedBase64, "JPEG", 10, 10, 100, 100); // Adjust position/size as needed doc.save("inverted-image.pdf"); } // Run the PDF generation createPDF();
Quick Notes:
- Async/Await: We use async/await to ensure we don't try to process the image before it's fully loaded.
- Transparency: The alpha channel is left untouched because inverting it would flip transparent areas to opaque (and vice versa), which is rarely desired.
- Hidden Canvas: The canvas we create isn't added to the DOM, so it stays invisible to users and gets cleaned up automatically.
内容的提问来源于stack exchange,提问作者kaushalpranav
相关产品推荐
相关产品推荐

