You can edit the below JavaScript code to customize the image tool.
Apply Changes
// Helper for QRious library loading, defined in a scope that persists across processImage calls
let qriousLoadPromise = null;
async function ensureQRiousIsLoaded() {
if (typeof window.QRious !== 'undefined') {
return; // Already loaded
}
if (!qriousLoadPromise) {
qriousLoadPromise = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js';
script.onload = () => {
resolve();
};
script.onerror = () => {
qriousLoadPromise = null; // Allow retry on next call if loading failed
reject(new Error('Failed to load QRious library.'));
};
document.head.appendChild(script);
});
}
// This function returns the promise, which will be awaited by the caller.
return qriousLoadPromise;
}
async function processImage(originalImg, qrSize = 256, errorCorrectionLevel = 'L', foregroundColor = '#000000', backgroundColor = '#FFFFFF', padding = 10, imageOutputFormat = 'image/png', imageQuality = 0.92, maxImageDimension = 100) {
// Helper function to create an error canvas
function createErrorCanvas(messages, errorTitle) {
const errorCanvas = document.createElement('canvas');
errorCanvas.width = qrSize;
errorCanvas.height = qrSize;
const ctx = errorCanvas.getContext('2d');
ctx.fillStyle = 'rgb(220, 220, 220)'; // Light gray background for error
if (errorTitle && errorTitle.toLowerCase().includes("data too long")) {
ctx.fillStyle = 'rgb(255, 100, 100)'; // Reddish for critical user-fixable errors
}
ctx.fillRect(0, 0, qrSize, qrSize);
const fontSize = Math.max(8, Math.min(16, Math.floor(qrSize / 16)));
const lineHeight = fontSize * 1.25;
ctx.font = `${fontSize}px Arial`;
ctx.fillStyle = errorTitle && errorTitle.toLowerCase().includes("data too long") ? 'white' : 'black';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const totalTextHeight = (messages.length -1) * lineHeight;
let yStart = (qrSize / 2) - (totalTextHeight / 2);
for (let i = 0; i < messages.length; i++) {
ctx.fillText(messages[i], qrSize / 2, yStart + (i * lineHeight));
}
return errorCanvas;
}
try {
await ensureQRiousIsLoaded();
} catch (err) {
console.error(err.message);
return createErrorCanvas(["Failed to load", "QR library.", "Check network."]);
}
let imageToEncodeDataURL;
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
let { width: imgWidth, height: imgHeight } = originalImg;
if (imgWidth === 0 || imgHeight === 0) {
// Handle unloaded or broken image: use a 1x1 transparent pixel to avoid errors
tempCanvas.width = 1;
tempCanvas.height = 1;
// Note: A 1x1 transparent PNG data URL is very small and will encode fine.
// tempCtx is transparent black by default.
} else if (imgWidth > maxImageDimension || imgHeight > maxImageDimension) {
if (imgWidth > imgHeight) {
tempCanvas.width = maxImageDimension;
tempCanvas.height = Math.max(1, Math.round((imgHeight / imgWidth) * maxImageDimension)); // Ensure at least 1px
} else {
tempCanvas.height = maxImageDimension;
tempCanvas.width = Math.max(1, Math.round((imgWidth / imgHeight) * maxImageDimension)); // Ensure at least 1px
}
tempCtx.drawImage(originalImg, 0, 0, tempCanvas.width, tempCanvas.height);
} else {
tempCanvas.width = imgWidth;
tempCanvas.height = imgHeight;
tempCtx.drawImage(originalImg, 0, 0, tempCanvas.width, tempCanvas.height);
}
try {
if (imageOutputFormat.toLowerCase() === 'image/jpeg') {
imageToEncodeDataURL = tempCanvas.toDataURL(imageOutputFormat, imageQuality);
} else {
// For 'image/png' or other formats that don't use quality param
imageToEncodeDataURL = tempCanvas.toDataURL(imageOutputFormat);
}
} catch (e) {
console.error("Error converting image to Data URL:", e);
return createErrorCanvas(["Image Conversion", "Error.", String(e.name || "Error")]);
}
const qrCanvas = document.createElement('canvas');
// QRious will set the canvas width/height based on its 'size' option.
try {
new window.QRious({
element: qrCanvas,
value: imageToEncodeDataURL,
level: errorCorrectionLevel, // L, M, Q, H
size: qrSize,
foreground: foregroundColor,
background: backgroundColor,
padding: padding < 0 ? null : padding // Use QRious default padding if our padding is < 0
});
} catch (e) {
console.error("Error generating QR code:", e);
const errorMessages = e.message && e.message.toLowerCase().includes("too long") ?
["Data too long", "for QR code.", "Reduce image size", "or complexity."] :
["QR Generation", "Error.", String(e.name || "Error")];
return createErrorCanvas(errorMessages, e.message || String(e.name || "Error"));
}
return qrCanvas;
}
Apply Changes