You can edit the below JavaScript code to customize the image tool.
async function processImage(originalImg, fontSize = 10, threshold = 128, fontColor = 'green', backgroundColor = 'black') {
// Validate and sanitize parameters
fontSize = Math.max(1, Math.floor(fontSize)); // Ensure fontSize is a positive integer
threshold = Math.max(0, Math.min(255, threshold)); // Clamp threshold to 0-255
const originalWidth = originalImg.naturalWidth || originalImg.width;
const originalHeight = originalImg.naturalHeight || originalImg.height;
// Create the output canvas with the same dimensions as the original image
const outputCanvas = document.createElement('canvas');
outputCanvas.width = originalWidth;
outputCanvas.height = originalHeight;
const outputCtx = outputCanvas.getContext('2d');
// If image has no dimensions (e.g., not loaded or invalid), return an empty canvas
// filled with the background color.
if (originalWidth === 0 || originalHeight === 0) {
console.warn("Image has zero dimensions or is not fully loaded.");
outputCtx.fillStyle = backgroundColor;
outputCtx.fillRect(0, 0, outputCanvas.width, outputCanvas.height);
// Optionally, draw a message if canvas is small but >0
if (outputCanvas.width > 0 && outputCanvas.height > 0) {
outputCtx.fillStyle = fontColor === backgroundColor ? (backgroundColor === 'black' ? 'white' : 'black') : fontColor;
outputCtx.font = `${Math.min(fontSize, Math.min(originalWidth,originalHeight)/2)}px Arial`;
outputCtx.textAlign = 'center';
outputCtx.textBaseline = 'middle';
outputCtx.fillText('No Image', outputCanvas.width/2, outputCanvas.height/2);
}
return outputCanvas;
}
// 1. Create a temporary source canvas to draw the original image and get its pixel data.
const sourceCanvas = document.createElement('canvas');
sourceCanvas.width = originalWidth;
sourceCanvas.height = originalHeight;
const sourceCtx = sourceCanvas.getContext('2d', {
willReadFrequently: true, // Hint for optimization for frequent getImageData calls
});
try {
// Draw the image onto the source canvas. This needs to be done to access pixel data.
sourceCtx.drawImage(originalImg, 0, 0, originalWidth, originalHeight);
} catch (e) {
console.error("Error drawing image onto source canvas. The Image object might be invalid or not fully loaded.", e);
// Fallback: fill outputCanvas with background color and an error message
outputCtx.fillStyle = backgroundColor;
outputCtx.fillRect(0, 0, originalWidth, originalHeight);
const errorFontColor = fontColor === backgroundColor ? (backgroundColor.toLowerCase() === '#000000' || backgroundColor.toLowerCase() === 'black' ? 'white' : 'black') : fontColor;
outputCtx.fillStyle = errorFontColor;
outputCtx.font = `${Math.min(fontSize * 1.5, Math.min(originalWidth, originalHeight) / 5, 24)}px Arial`;
outputCtx.textAlign = 'center';
outputCtx.textBaseline = 'middle';
outputCtx.fillText('Error: Could not draw image', originalWidth / 2, originalHeight / 2, originalWidth * 0.9);
return outputCanvas;
}
let sourceImageData;
try {
// Get pixel data from the source canvas.
sourceImageData = sourceCtx.getImageData(0, 0, originalWidth, originalHeight);
} catch (e) {
console.error("Error getting image data. This can be due to cross-origin restrictions if the image source is external and the canvas becomes tainted.", e);
// Fallback: fill outputCanvas with background color and an error message
outputCtx.fillStyle = backgroundColor;
outputCtx.fillRect(0, 0, originalWidth, originalHeight);
const errorFontColor = fontColor === backgroundColor ? (backgroundColor.toLowerCase() === '#000000' || backgroundColor.toLowerCase() === 'black' ? 'white' : 'black') : fontColor;
outputCtx.fillStyle = errorFontColor;
outputCtx.font = `${Math.min(fontSize * 1.5, Math.min(originalWidth, originalHeight) / 5, 24)}px Arial`;
outputCtx.textAlign = 'center';
outputCtx.textBaseline = 'middle';
outputCtx.fillText('Error: Tainted canvas / CORS', originalWidth / 2, originalHeight / 2, originalWidth * 0.9);
return outputCanvas;
}
const data = sourceImageData.data;
// 2. Prepare the output canvas
// Fill background
outputCtx.fillStyle = backgroundColor;
outputCtx.fillRect(0, 0, outputCanvas.width, outputCanvas.height);
// Set text properties for drawing the binary code
outputCtx.fillStyle = fontColor;
outputCtx.font = `${fontSize}px monospace`; // Use monospace for more uniform character widths
outputCtx.textAlign = 'center'; // Center characters horizontally in their cell
outputCtx.textBaseline = 'middle'; // Center characters vertically in their cell
// 3. Process the image and draw binary characters ('0' or '1')
// Iterate over the image in blocks (cells), each of size approx. fontSize x fontSize
for (let y = 0; y < originalHeight; y += fontSize) {
for (let x = 0; x < originalWidth; x += fontSize) {
let sumGrayscale = 0;
let numPixelsInBlock = 0;
// Define the actual dimensions of the current block, clamping to image boundaries
// This handles cases where the block is at the edge of the image.
const blockWidth = Math.min(fontSize, originalWidth - x);
const blockHeight = Math.min(fontSize, originalHeight - y);
// Calculate the average grayscale value for the pixels in the current block
for (let subPixelY = 0; subPixelY < blockHeight; subPixelY++) {
for (let subPixelX = 0; subPixelX < blockWidth; subPixelX++) {
const currentPixelX = x + subPixelX;
const currentPixelY = y + subPixelY;
// Get the starting index of the Red component for the current pixel in the ImageData array
const R_INDEX = (currentPixelY * originalWidth + currentPixelX) * 4;
const r = data[R_INDEX];
const g = data[R_INDEX + 1];
const b = data[R_INDEX + 2];
// const alpha = data[R_INDEX + 3]; // Alpha component is not used in this grayscale calculation
// Convert RGB to grayscale using the standard luminance formula
sumGrayscale += (0.299 * r + 0.587 * g + 0.114 * b);
numPixelsInBlock++;
}
}
// Calculate average grayscale. Default to 0 (black) if block is empty (should not happen with current logic)
const avgGrayscale = numPixelsInBlock > 0 ? sumGrayscale / numPixelsInBlock : 0;
// Determine whether to draw a '0' (for darker areas) or '1' (for brighter areas)
const charToDraw = avgGrayscale < threshold ? '0' : '1';
// Draw the character. It will be centered within a theoretical cell of fontSize x fontSize,
// whose top-left corner is (x,y). The center of this cell is (x + fontSize/2, y + fontSize/2).
outputCtx.fillText(charToDraw, x + fontSize / 2, y + fontSize / 2);
}
}
return outputCanvas;
}
Free Image Tool Creator
Can't find the image tool you're looking for? Create one based on your own needs now!
The Image Binary Code Filter Effect Tool transforms images into a binary representation using ‘0’s and ‘1’s based on the grayscale values of the pixels. Users can customize the font size, color, and background color of the resulting image. This tool is suitable for creating unique artistic effects, enhancing digital artwork, and generating code-like representations of images for creative projects, presentations, or social media content.