You can edit the below JavaScript code to customize the image tool.
function processImage(originalImg, threshold = 128) {
// Ensure threshold is a valid number, defaulting to 128 if not.
// Number(string) handles string-to-number conversion.
// Number(undefined) (if threshold is not passed) is NaN.
// Number(null) is 0.
const numericThreshold = Number(threshold);
let finalThreshold = isNaN(numericThreshold) ? 128 : numericThreshold;
// It's common for thresholds in image processing to be within 0-255.
// Clamping the threshold to this range can make it more robust.
// finalThreshold = Math.max(0, Math.min(255, finalThreshold));
// However, without explicit instruction, we'll use the value as is or derived.
// If threshold is outside 0-255, values like luminance < -10 (always false for non-negative luminance)
// or luminance < 300 (always true for luminance <=255) yield consistent all-white/all-black results.
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error("Canvas 2D context is not available.");
// Return a placeholder div with an error message, as canvas cannot be used.
const errorDiv = document.createElement('div');
errorDiv.textContent = "Error: Canvas 2D context not available. Cannot process image.";
errorDiv.style.color = "red";
errorDiv.style.padding = "10px";
errorDiv.style.border = "1px solid black";
return errorDiv;
}
// Use naturalWidth/naturalHeight for the actual image dimensions.
// These are 0 if the image isn't loaded or is invalid.
const naturalWidth = originalImg.naturalWidth;
const naturalHeight = originalImg.naturalHeight;
// Check if the image is loaded and has valid dimensions.
// originalImg.complete indicates if the browser has fetched the image.
if (!originalImg.complete || naturalWidth === 0 || naturalHeight === 0) {
console.warn("Image is not fully loaded, has zero dimensions, or is invalid.");
// Create a canvas with an HMTL-friendly error message.
canvas.width = 300; // Arbitrary size for error message display
canvas.height = 100;
ctx.fillStyle = "#f0f0f0"; // Light gray background
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "black";
ctx.font = "16px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Error: Image not loaded or invalid.", canvas.width / 2, canvas.height / 2);
return canvas;
}
canvas.width = naturalWidth;
canvas.height = naturalHeight;
try {
// Draw the original image onto the canvas.
ctx.drawImage(originalImg, 0, 0, naturalWidth, naturalHeight);
} catch (e) {
// This might happen for various reasons, e.g. if originalImg is not a valid source.
console.error("Error drawing image to canvas:", e);
ctx.fillStyle = "#f0f0f0";
ctx.fillRect(0, 0, canvas.width, canvas.height); // Clear canvas
ctx.fillStyle = "black";
ctx.font = "16px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Error: Could not draw image.", canvas.width / 2, canvas.height / 2);
return canvas;
}
let imageData;
try {
// Get the pixel data from the canvas.
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
} catch (e) {
// This can happen due to CORS issues if the image is from a different origin
// and the canvas becomes "tainted".
console.error("Could not get image data, possibly due to CORS policy:", e);
// Canvas is already sized to the image; draw an error message on it.
ctx.fillStyle = "#f0f0f0"; // Light gray background
ctx.fillRect(0, 0, canvas.width, canvas.height); // Clear potentially tainted drawImage
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
// Adjust font size for message if canvas is very small
let fontSize = 16;
if (canvas.width < 250 || canvas.height < 50) {
fontSize = Math.min(canvas.width / 15, canvas.height / 3, 12); // Heuristic for small canvas
}
ctx.font = `${fontSize}px Arial`;
ctx.fillText("Error: Cannot process pixels.", canvas.width / 2, canvas.height / 2 - fontSize / 2);
if (fontSize > 8) { // Add second line if there's space
ctx.fillText("(Likely CORS security issue)", canvas.width / 2, canvas.height / 2 + fontSize /2);
}
return canvas;
}
const data = imageData.data; // This is a Uint8ClampedArray: [R, G, B, A, R, G, B, A, ...]
// Iterate over each pixel (4 bytes: R, G, B, A)
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// Alpha channel (data[i + 3]) is not modified.
// Calculate luminance (perceived brightness).
// Standard formula: L = 0.299*R + 0.587*G + 0.114*B
const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
// Apply threshold: if luminance is less than threshold, pixel becomes black; otherwise, white.
const value = luminance < finalThreshold ? 0 : 255;
data[i] = value; // Red channel
data[i + 1] = value; // Green channel
data[i + 2] = value; // Blue channel
}
// Put the modified pixel data back onto the canvas.
ctx.putImageData(imageData, 0, 0);
return canvas;
}
Free Image Tool Creator
Can't find the image tool you're looking for? Create one based on your own needs now!
The Image High Contrast Filter Tool allows users to enhance images by applying a high contrast filter that converts image colors to stark black and white based on a specified luminance threshold. This tool is useful for improving visibility in images, making them suitable for various applications such as printing, graphic design, and enhancing readability in low-quality photographs or documents. Users can easily adjust the threshold to control the contrast level, making it versatile for different image types and desired outcomes.