You can edit the below JavaScript code to customize the image tool.
function processImage(originalImg, printSizeStr = "4x6", dpi = 300) {
// --- 1. Validate parameters and calculate target dimensions ---
let currentDpi = dpi;
if (typeof currentDpi !== 'number' || currentDpi <= 0) {
console.warn(`Invalid DPI: ${dpi}. Must be a positive number. Defaulting to 300 DPI.`);
currentDpi = 300;
}
let targetWidthInches, targetHeightInches;
// Ensure printSizeStr is treated as a string for robust parsing
const sizeParts = String(printSizeStr).toLowerCase().split('x');
if (sizeParts.length === 2) {
targetWidthInches = parseFloat(sizeParts[0]);
targetHeightInches = parseFloat(sizeParts[1]);
}
let inputSizeValid = true;
if (isNaN(targetWidthInches) || isNaN(targetHeightInches) || targetWidthInches <= 0 || targetHeightInches <= 0) {
console.warn(`Invalid printSize: "${printSizeStr}". Expected format "WIDTHxHEIGHT" (e.g., "4x6") with positive numbers. Defaulting to 4x6 inches.`);
targetWidthInches = 4;
targetHeightInches = 6;
inputSizeValid = false;
}
let targetWidthPx = Math.round(targetWidthInches * currentDpi);
let targetHeightPx = Math.round(targetHeightInches * currentDpi);
// This variable will hold the string representation of the इंच dimensions ultimately used for calculation.
let effectiveInchesStr = inputSizeValid ? printSizeStr : `${targetWidthInches}x${targetHeightInches}`;
if (targetWidthPx <= 0 || targetHeightPx <= 0) {
const fallbackWidthInches = 4;
const fallbackHeightInches = 6;
// If original currentDpi was problematic (e.g. extremely small positive), also reset to a sensible DPI for this fallback.
const sensibleDpiForMessage = (currentDpi > 0 && currentDpi < 50) ? 300 : currentDpi; // If dpi is tiny let's use 300 for meaningful message
console.warn(`Calculated pixel dimensions (${targetWidthPx}x${targetHeightPx}) for "${targetWidthInches}x${targetHeightInches}" inches at ${currentDpi} DPI are invalid. Defaulting to ${fallbackWidthInches}x${fallbackHeightInches} inches @ ${sensibleDpiForMessage} DPI for pixel calculation.`);
targetWidthInches = fallbackWidthInches;
targetHeightInches = fallbackHeightInches;
currentDpi = sensibleDpiForMessage; // Update currentDpi if it was part of the problem or for consistency in messages.
targetWidthPx = Math.round(targetWidthInches * currentDpi);
targetHeightPx = Math.round(targetHeightInches * currentDpi);
effectiveInchesStr = `${targetWidthInches}x${targetHeightInches}`; // Update effective inches string
}
// --- 2. Validate original image ---
const origW = originalImg.naturalWidth || originalImg.width;
const origH = originalImg.naturalHeight || originalImg.height;
if (!origW || !origH || origW <= 0 || origH <= 0) { // Check for strictly positive dimensions
console.error("Original image is invalid or not loaded properly (dimensions are zero or negative).");
const errorCanvas = document.createElement('canvas');
errorCanvas.width = targetWidthPx;
errorCanvas.height = targetHeightPx;
const ctx = errorCanvas.getContext('2d');
ctx.fillStyle = '#EEEEEE';
ctx.fillRect(0, 0, errorCanvas.width, errorCanvas.height);
ctx.fillStyle = '#CC0000';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Adjust font size dynamically based on canvas size
const baseFontSize = Math.max(12, Math.min(targetWidthPx / 18, targetHeightPx / 12, 20)); // Cap max font size for title
ctx.font = `bold ${baseFontSize}px Arial`;
const message = "Error: Source image invalid or not loaded.";
const textYPosition = errorCanvas.height / 2 - baseFontSize * 0.7; // Position for first line
ctx.fillText(message, errorCanvas.width / 2, textYPosition);
const detailFontSize = Math.max(10, Math.min(targetWidthPx / 25, targetHeightPx / 20, 14)); // Cap max font size for details
ctx.font = `${detailFontSize}px Arial`;
ctx.fillStyle = '#333333';
ctx.fillText(`Target: ${effectiveInchesStr} @ ${currentDpi}DPI (${targetWidthPx}x${targetHeightPx}px)`, errorCanvas.width / 2, textYPosition + baseFontSize * 1.1);
return errorCanvas;
}
// --- 3. Create canvas and draw ---
const canvas = document.createElement('canvas');
canvas.width = targetWidthPx;
canvas.height = targetHeightPx;
const ctx = canvas.getContext('2d');
// Set image smoothing options for best quality resizing
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
// Calculate aspect ratios
const origAR = origW / origH;
const targetAR = targetWidthPx / targetHeightPx; // targetWidthPx and targetHeightPx are guaranteed > 0 here
let sx = 0, sy = 0, sWidth = origW, sHeight = origH;
// Determine cropping strategy to fill the target dimensions while maintaining aspect ratio
if (origAR > targetAR) {
// Original image is wider than target aspect ratio (landscape-like compared to target).
// Crop sides of original image. Source height (sHeight) is original height.
sWidth = origH * targetAR; // Calculate source width to match target aspect ratio
sx = (origW - sWidth) / 2; // Center the crop region horizontally
} else if (origAR < targetAR) {
// Original image is taller than target aspect ratio (portrait-like compared to target).
// Crop top/bottom of original image. Source width (sWidth) is original width.
sHeight = origW / targetAR; // Calculate source height to match target aspect ratio
sy = (origH - sHeight) / 2; // Center the crop region vertically
}
// If origAR === targetAR, no cropping is needed (sx, sy = 0, sWidth = origW, sHeight = origH).
// Draw the (potentially cropped) original image onto the canvas, scaled to fill target dimensions.
// sx, sy, sWidth, sHeight define the rectangular area of the source image to draw.
// 0, 0, targetWidthPx, targetHeightPx define where it's drawn on the destination canvas.
ctx.drawImage(originalImg, sx, sy, sWidth, sHeight, 0, 0, targetWidthPx, targetHeightPx);
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 Resizer For Common Print Sizes’ tool enables users to easily resize images to standard print dimensions, such as 4×6 inches or 5×7 inches, while maintaining high quality. It allows users to specify the desired print size and the dots per inch (DPI) for optimal print resolution. This tool is particularly useful for photographers, graphic designers, or anyone needing to prepare images for printing, ensuring that the resized images meet specific size and quality requirements.