Photo Resizer in KB – Exact Size Compression
/* — CSS SEPARATION START — */
@import url(‘https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap’);:root {
–primary: #0EA5E9; /* Sky-500 */
–bg-dark: #0F172A;
}body {
font-family: ‘Inter’, sans-serif;
transition: background-color 0.3s, color 0.3s;
}/* Animated Progress Bar */
.progress-bar-striped {
background-image: linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);
background-size: 1rem 1rem;
animation: progress-bar-stripes 1s linear infinite;
}@keyframes progress-bar-stripes {
0% { background-position: 1rem 0; }
100% { background-position: 0 0; }
}/* Loading Spinner */
.loader {
border: 3px solid #f3f3f3;
border-radius: 50%;
border-top: 3px solid #0EA5E9;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
}@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}/* Dark Mode */
.dark body {
background-color: var(–bg-dark);
color: #F9FAFB;
}
.dark .card {
background-color: #1E293B;
border-color: #334155;
}
.dark input, .dark select {
background-color: #334155;
color: white;
border-color: #475569;
}
/* — CSS SEPARATION END — */
tailwind.config = {
darkMode: ‘class’,
theme: {
extend: {
colors: {
primary: ‘#0EA5E9’,
}
}
}
}
Need a photo under 50KB for an application? Enter your target size and let us handle the compression math.
Quick Select
20KB
50KB
100KB
200KB
Drag & Drop Photos Here or click to browse (JPG, PNG, WEBP)
Select Images
Processing Results Target: 50KB
Download All
Start Over
// — JAVASCRIPT SEPARATION START —// DOM Elements
const dropzone = document.getElementById(‘dropzone’);
const fileInput = document.getElementById(‘fileInput’);
const inpKb = document.getElementById(‘inp-kb’);
const resultsArea = document.getElementById(‘results-area’);
const resultsList = document.getElementById(‘results-list’);
const displayTargetKb = document.getElementById(‘display-target-kb’);
const canvas = document.getElementById(‘process-canvas’);
const ctx = canvas.getContext(‘2d’);
const btnDownloadAll = document.getElementById(‘btn-download-all’);let isDarkMode = false;
let processedBlobs = []; // Store blobs for potential zip download (not implemented fully in client-only without lib, but ready structure)// — Event Listeners —
dropzone.addEventListener(‘click’, (e) => {
// Prevent click when clicking button inside (handled by bubbling but nice to be explicit if needed)
fileInput.click();
});
dropzone.addEventListener(‘dragover’, (e) => {
e.preventDefault();
dropzone.classList.add(‘border-sky-500’, ‘bg-sky-50’, ‘dark:bg-slate-700’);
});
dropzone.addEventListener(‘dragleave’, () => {
dropzone.classList.remove(‘border-sky-500’, ‘bg-sky-50’, ‘dark:bg-slate-700’);
});
dropzone.addEventListener(‘drop’, (e) => {
e.preventDefault();
dropzone.classList.remove(‘border-sky-500’, ‘bg-sky-50’, ‘dark:bg-slate-700’);
if(e.dataTransfer.files.length) handleFiles(e.dataTransfer.files);
});fileInput.addEventListener(‘change’, (e) => {
if(e.target.files.length) handleFiles(e.target.files);
});inpKb.addEventListener(‘input’, (e) => {
displayTargetKb.innerText = `${e.target.value}KB`;
});// — Core Functions —function setKB(val) {
inpKb.value = val;
displayTargetKb.innerText = `${val}KB`;
}function handleFiles(files) {
resultsArea.classList.remove(‘hidden’);
const targetKB = parseInt(inpKb.value) || 50;
const targetBytes = targetKB * 1024;Array.from(files).forEach(file => {
if (!file.type.match(‘image.*’)) return;
// Create UI Shell
const uiId = Math.random().toString(36).substr(2, 9);
createResultItem(uiId, file);// Process
processImage(file, targetBytes, uiId);
});
}function createResultItem(id, file) {
const div = document.createElement(‘div’);
div.id = id;
div.className = ‘card bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm border border-gray-200 dark:border-slate-700 flex flex-col sm:flex-row items-center gap-4 animate-fade-in’;
div.innerHTML = `
${file.name} Original: ${formatBytes(file.size)}
Compressing…
Wait
`;
resultsList.prepend(div);
}function processImage(file, targetBytes, uiId) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
// Logic: Resize/Compress loop
compressToTarget(img, file.type, targetBytes).then(result => {
updateResultUI(uiId, file, result.blob, result.finalQ, img.src);
}).catch(err => {
console.error(err);
markError(uiId, “Compression Failed”);
});
};
};
}async function compressToTarget(img, originalType, targetBytes) {
// Setup Canvas
const w = img.width;
const h = img.height;
canvas.width = w;
canvas.height = h;
// Fill background for JPG (prevent black bg on transparent pngs)
ctx.fillStyle = ‘#FFFFFF’;
ctx.fillRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);let minQ = 0.01;
let maxQ = 1.0;
let quality = 0.9;
let blob = null;
let iterations = 0;
// Prefer JPEG for size reduction tasks unless user specifically needs transparency (which JPEG kills)
// But strict “KB” tools usually output JPG to guarantee size.
// Let’s force JPG for maximum compression capability, or WEBP.
// PNG does not support quality parameter in toBlob standard.
const format = ‘image/jpeg’;// Binary search for quality
while (iterations canvas.toBlob(r, format, quality));
// Check if we are close enough (under target but not too small, or just under target)
if (blob.size targetBytes * 0.8) {
return { blob, finalQ: quality };
}if (blob.size > targetBytes) {
maxQ = quality; // Quality too high
} else {
minQ = quality; // Quality can be higher
}
quality = (minQ + maxQ) / 2;
iterations++;
}// If we failed to get under target with quality alone (still too big at q=0.01?),
// we might need to resize dimensions.
// For this simple version, we return the best effort blob.
if (blob.size > targetBytes) {
// Fallback: Resize dimensions by 50% and try one last desperate compression
// Real advanced tools would loop this too.
const scale = 0.7;
canvas.width = w * scale;
canvas.height = h * scale;
ctx.fillStyle = ‘#FFFFFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
blob = await new Promise(r => canvas.toBlob(r, format, 0.5));
}return { blob, finalQ: quality };
}function updateResultUI(id, originalFile, blob, quality, previewSrc) {
const div = document.getElementById(id);
if(!div) return;const url = URL.createObjectURL(blob);
const sizeDiff = originalFile.size – blob.size;
const percentSaved = ((sizeDiff / originalFile.size) * 100).toFixed(0);
const isSuccess = blob.size <= (parseInt(inpKb.value) * 1024 * 1.05); // 5% tolerance
// Generate Name
const name = `compressed_${originalFile.name.split('.')[0]}.jpg`;div.innerHTML = `
${name}
Original: ${formatBytes(originalFile.size)}
New: ${formatBytes(blob.size)}
Saved ${percentSaved}%
`;
// Store for “Download All” (Not implemented fully to keep file count 1, but placeholder)
processedBlobs.push({ blob, name });
if(processedBlobs.length > 1) {
// btnDownloadAll.classList.remove(‘hidden’); // Requires JSZip for real browser zip
}
}function markError(id, msg) {
const div = document.getElementById(id);
if(div) {
div.querySelector(‘.status-text’).innerText = msg;
div.querySelector(‘.status-text’).classList.add(‘text-red-500’);
}
}function formatBytes(bytes) {
if (bytes === 0) return ‘0 Bytes’;
const k = 1024;
const sizes = [‘Bytes’, ‘KB’, ‘MB’];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ‘ ‘ + sizes[i];
}function resetAll() {
processedBlobs = [];
resultsList.innerHTML = ”;
resultsArea.classList.add(‘hidden’);
fileInput.value = ”;
}// — Dark Mode —
function toggleDarkMode() {
isDarkMode = !isDarkMode;
document.documentElement.classList.toggle(‘dark’);
const icon = document.getElementById(‘theme-icon’);
if(isDarkMode) {
icon.classList.remove(‘fa-moon’);
icon.classList.add(‘fa-sun’);
} else {
icon.classList.remove(‘fa-sun’);
icon.classList.add(‘fa-moon’);
}
}// — JAVASCRIPT SEPARATION END —
Photo Resizer in KB: Overview and Usage Tips Use the Photo Resizer in KB utility for tasks involving digital images. Review the tool interface for supported inputs and settings. For file-based tasks, keep a copy of your original file and check the output before using it.
Steps to get started Read the supported formats or input requirements shown in the tool. Choose the available options appropriate to your task. Run the tool and review its result for accuracy and quality. Related resources Try Image Compressor or Image Resizer for another document or digital task.