ReFixIMG / index.html
pakdeveloper's picture
Update index.html
e5660eb verified
Raw History Blame Contribute Delete
27.9 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ReFixIMG | Online Image Tools (Compress, Resize, Convert)</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<style>
/* Custom styles for a cleaner interface */
body {
font-family: 'Inter', sans-serif;
background-color: #f4f7fa; /* Light background */
}
.tool-card {
transition: all 0.2s ease-in-out;
cursor: pointer;
}
.tool-card:hover {
transform: translateY(-2px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.active-tool {
border-color: #ef4444; /* Red border for active tool */
background-color: #fef2f2; /* Light red background */
}
#drop-zone {
min-height: 250px;
border: 4px dashed #9ca3af;
transition: all 0.3s ease;
/* Added cursor style to indicate interactivity */
cursor: pointer;
}
#drop-zone.drag-over {
border-color: #ef4444;
background-color: #fef2f2;
}
#preview-canvas {
max-width: 100%;
height: auto;
border-radius: 0.5rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
.btn-primary {
background-image: linear-gradient(to right, #ef4444, #dc2626);
transition: transform 0.1s;
}
.btn-primary:hover {
transform: scale(1.02);
box-shadow: 0 4px 6px -1px rgba(220, 38, 38, 0.4);
}
</style>
</head>
<body class="p-4 md:p-8">
<header class="text-center mb-10">
<h1 class="text-5xl font-extrabold text-gray-800">ReFix<span class="text-red-600">IMG</span></h1>
<p class="text-xl text-gray-500 mt-2">The fastest, free web app for easy image modification.</p>
</header>
<section class="max-w-7xl mx-auto mb-10">
<h2 class="text-2xl font-semibold text-gray-700 mb-4">Choose Your Tool</h2>
<div id="tool-selector" class="grid grid-cols-1 sm:grid-cols-3 gap-6">
<div id="tool-compress" class="tool-card p-6 border-2 border-gray-200 rounded-xl shadow-lg bg-white active-tool" data-tool="compress">
<svg class="w-8 h-8 text-red-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
<h3 class="font-bold text-lg text-gray-800">Compress IMAGE</h3>
<p class="text-sm text-gray-500">Reduce JPG, PNG, and WebP file size while maintaining quality.</p>
</div>
<div id="tool-resize" class="tool-card p-6 border-2 border-gray-200 rounded-xl shadow-lg bg-white" data-tool="resize">
<svg class="w-8 h-8 text-red-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10m0 0h4m-4 0l4-4m-4 4l4 4m8-12v10m0 0h4m-4 0l4-4m-4 4l4 4"></path></svg>
<h3 class="font-bold text-lg text-gray-800">Resize IMAGE</h3>
<p class="text-sm text-gray-500">Change the width and height of your images in pixels.</p>
</div>
<div id="tool-convert" class="tool-card p-6 border-2 border-gray-200 rounded-xl shadow-lg bg-white" data-tool="convert">
<svg class="w-8 h-8 text-red-600 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
<h3 class="font-bold text-lg text-gray-800">Convert IMAGE</h3>
<p class="text-sm text-gray-500">Convert images to JPG, PNG, or WebP format easily.</p>
</div>
</div>
</section>
<main class="max-w-7xl mx-auto bg-white p-8 rounded-xl shadow-2xl">
<div id="drop-zone" class="flex flex-col items-center justify-center p-8 border-gray-400 rounded-xl text-center mb-8"
onclick="document.getElementById('file-input').click()">
<svg class="w-12 h-12 text-gray-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path></svg>
<p class="text-xl text-gray-600 font-semibold mb-3">Drop images here or select them from your device.</p>
<p class="text-sm text-gray-400 mb-6">Supported formats: JPG, PNG, GIF, WebP (Only the first image will be processed).</p>
<input type="file" id="file-input" accept="image/*" class="hidden" multiple>
<button class="btn-primary text-white font-bold py-3 px-8 rounded-lg shadow-md hover:shadow-lg focus:outline-none focus:ring-4 focus:ring-red-500 focus:ring-opacity-50"
onclick="event.stopPropagation(); document.getElementById('file-input').click()">
SELECT IMAGE
</button>
</div>
<div id="processing-area" class="hidden grid grid-cols-1 lg:grid-cols-3 gap-8">
<div class="lg:col-span-1 p-6 bg-gray-50 rounded-xl border border-gray-200">
<h3 class="text-xl font-bold text-gray-700 mb-4">Current Tool Settings</h3>
<p id="file-info" class="text-sm text-gray-500 mb-4"></p>
<div id="settings-compress" class="tool-settings">
<label for="quality-slider" class="block text-sm font-medium text-gray-700 mb-2">JPEG/WebP Quality (<span id="quality-value">85</span>%)</label>
<input type="range" id="quality-slider" min="10" max="100" value="85" step="5" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
<label for="compress-format" class="block text-sm font-medium text-gray-700 mt-4 mb-2">Output Format</label>
<select id="compress-format" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-red-500 focus:border-red-500">
<option value="image/jpeg">JPG (Best Compression)</option>
<option value="image/webp">WebP</option>
<option value="image/png">PNG (Lossless, less compression)</option>
</select>
</div>
<div id="settings-resize" class="tool-settings hidden">
<div class="flex space-x-4 mb-4">
<div class="flex-1">
<label for="resize-width" class="block text-sm font-medium text-gray-700 mb-2">Width (px)</label>
<input type="number" id="resize-width" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-red-500 focus:border-red-500" value="0" min="1">
</div>
<div class="flex-1">
<label for="resize-height" class="block text-sm font-medium text-gray-700 mb-2">Height (px)</label>
<input type="number" id="resize-height" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-red-500 focus:border-red-500" value="0" min="1">
</div>
</div>
<div class="flex items-center">
<input type="checkbox" id="aspect-lock" checked class="h-4 w-4 text-red-600 border-gray-300 rounded focus:ring-red-500">
<label for="aspect-lock" class="ml-2 text-sm text-gray-700">Lock Aspect Ratio</label>
</div>
<p class="text-xs text-gray-500 mt-2">Enter 0 in one field to calculate the dimension based on aspect ratio.</p>
</div>
<div id="settings-convert" class="tool-settings hidden">
<label for="target-format" class="block text-sm font-medium text-gray-700 mb-2">Target Format</label>
<select id="target-format" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-red-500 focus:border-red-500">
<option value="image/jpeg">JPG</option>
<option value="image/png">PNG</option>
<option value="image/webp">WebP</option>
</select>
</div>
<button id="process-button" class="btn-primary text-white font-bold py-3 w-full rounded-lg shadow-md mt-6" onclick="ImageToolApp.processImage()">
APPLY CHANGES
</button>
</div>
<div class="lg:col-span-2 p-6 bg-gray-50 rounded-xl border border-gray-200">
<h3 class="text-xl font-bold text-gray-700 mb-4">Preview & Download</h3>
<div id="loading-indicator" class="hidden text-center p-10">
<div class="animate-spin inline-block w-8 h-8 border-4 border-red-500 border-t-transparent rounded-full"></div>
<p class="mt-3 text-red-500">Processing image...</p>
</div>
<div id="preview-container" class="relative flex justify-center items-center bg-gray-200 p-4 rounded-lg">
<canvas id="preview-canvas" class="max-h-96"></canvas>
</div>
<!-- UPDATED RESULTS PANEL START -->
<div id="results-panel" class="hidden mt-6 flex flex-col sm:flex-row items-center justify-between p-4 rounded-xl">
<!-- Left: Size Information -->
<div class="text-center sm:text-left mb-4 sm:mb-0">
<p id="original-size" class="text-base text-gray-600">Original File Size: -</p>
<p id="new-size" class="text-xl font-bold text-gray-800 mt-1">New Size: -</p>
</div>
<!-- Right: Action Buttons -->
<div class="flex flex-col sm:flex-row space-y-3 sm:space-y-0 sm:space-x-4 w-full sm:w-auto">
<button id="download-button" class="btn-primary text-white font-bold py-3 px-6 rounded-lg shadow-md w-full sm:w-auto" onclick="ImageToolApp.downloadImage()">
DOWNLOAD MODIFIED IMAGE
</button>
<button id="new-image-button" class="btn-primary text-white font-bold py-3 px-6 rounded-lg shadow-md w-full sm:w-auto" onclick="ImageToolApp.startNewImage()">
New Image
</button>
</div>
</div>
<!-- UPDATED RESULTS PANEL END -->
</div>
</div>
</main>
<script>
// Global utility to convert file size in bytes to a human-readable string
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// --- ImageToolApp Core Application Logic ---
const ImageToolApp = {
activeTool: 'compress',
originalImage: null, // Stores the original Image object
originalFile: null, // Stores the original File object (for size info)
canvas: document.getElementById('preview-canvas'),
ctx: null,
init() {
this.ctx = this.canvas.getContext('2d');
this.setupToolSelection();
this.setupFileInput();
this.setupDragAndDrop();
this.setupResizeListeners();
this.setupCompressListener();
// Initial state setup for resize input fields
document.getElementById('resize-width').value = 0;
document.getElementById('resize-height').value = 0;
},
setupToolSelection() {
document.querySelectorAll('.tool-card').forEach(card => {
card.addEventListener('click', () => {
this.setActiveTool(card.dataset.tool);
});
});
},
setActiveTool(toolName) {
this.activeTool = toolName;
// Update UI for active tool card
document.querySelectorAll('.tool-card').forEach(card => {
card.classList.remove('active-tool', 'border-red-600');
card.classList.add('border-gray-200');
});
document.getElementById(`tool-${toolName}`).classList.add('active-tool', 'border-red-600');
// Update UI for settings panel
document.querySelectorAll('.tool-settings').forEach(panel => {
panel.classList.add('hidden');
});
document.getElementById(`settings-${toolName}`).classList.remove('hidden');
// If an image is loaded, re-draw it to reset any previous changes
if (this.originalImage) {
this.loadImageOnCanvas(this.originalImage);
document.getElementById('results-panel').classList.add('hidden');
document.getElementById('process-button').textContent = 'APPLY CHANGES';
}
},
setupFileInput() {
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', (event) => {
if (event.target.files.length > 0) {
this.handleFile(event.target.files[0]);
}
});
},
setupDragAndDrop() {
const dropZone = document.getElementById('drop-zone');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, (e) => {
e.preventDefault();
e.stopPropagation();
}, false);
});
['dragenter', 'dragover'].forEach(eventName => {
dropZone.addEventListener(eventName, () => dropZone.classList.add('drag-over'), false);
});
['dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, () => dropZone.classList.remove('drag-over'), false);
});
dropZone.addEventListener('drop', (e) => {
const files = e.dataTransfer.files;
if (files.length > 0) {
this.handleFile(files[0]);
}
}, false);
},
setupCompressListener() {
const qualitySlider = document.getElementById('quality-slider');
const qualityValue = document.getElementById('quality-value');
qualitySlider.addEventListener('input', (e) => {
qualityValue.textContent = e.target.value;
});
},
setupResizeListeners() {
const widthInput = document.getElementById('resize-width');
const heightInput = document.getElementById('resize-height');
const aspectLock = document.getElementById('aspect-lock');
const calculateHeight = (newWidth) => {
if (this.originalImage && aspectLock.checked && newWidth > 0) {
return Math.round(newWidth * (this.originalImage.height / this.originalImage.width));
}
return 0;
};
const calculateWidth = (newHeight) => {
if (this.originalImage && aspectLock.checked && newHeight > 0) {
return Math.round(newHeight * (this.originalImage.width / this.originalImage.height));
}
return 0;
};
widthInput.addEventListener('input', () => {
const w = parseInt(widthInput.value) || 0;
if (aspectLock.checked) {
heightInput.value = calculateHeight(w);
}
});
heightInput.addEventListener('input', () => {
const h = parseInt(heightInput.value) || 0;
if (aspectLock.checked) {
widthInput.value = calculateWidth(h);
}
});
},
handleFile(file) {
if (!file || !file.type.startsWith('image/')) {
console.error("Not a valid image file.");
return;
}
this.originalFile = file;
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
this.originalImage = img;
this.loadImageOnCanvas(img);
this.updateFileInfo(file, img);
document.getElementById('processing-area').classList.remove('hidden');
document.getElementById('drop-zone').classList.add('hidden');
document.getElementById('results-panel').classList.add('hidden');
// Reset resize inputs to original dimensions
document.getElementById('resize-width').value = img.width;
document.getElementById('resize-height').value = img.height;
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
},
loadImageOnCanvas(img) {
// Resize canvas to original image dimensions for accurate drawing
this.canvas.width = img.width;
this.canvas.height = img.height;
// Clear and draw the image
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.drawImage(img, 0, 0, img.width, img.height);
// Set max height for visual preview
this.canvas.style.maxHeight = '400px';
this.canvas.style.maxWidth = '100%';
},
updateFileInfo(file, img) {
const infoText = `File: ${file.name} | Type: ${file.type} | Original Size: ${formatBytes(file.size)} | Dimensions: ${img.width}x${img.height}px`;
document.getElementById('file-info').textContent = infoText;
document.getElementById('original-size').textContent = `Original File Size: ${formatBytes(file.size)}`;
document.getElementById('new-size').textContent = `New Size: Calculating...`;
},
showLoading(isLoading) {
const loading = document.getElementById('loading-indicator');
if (isLoading) {
loading.classList.remove('hidden');
document.getElementById('process-button').disabled = true;
document.getElementById('process-button').textContent = 'Processing...';
} else {
loading.classList.add('hidden');
document.getElementById('process-button').disabled = false;
document.getElementById('process-button').textContent = 'APPLY CHANGES';
}
},
async processImage() {
if (!this.originalImage) return;
this.showLoading(true);
document.getElementById('results-panel').classList.add('hidden');
// We use a temporary canvas for manipulation to keep the main canvas clean for redrawing
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
let targetWidth = this.originalImage.width;
let targetHeight = this.originalImage.height;
let mimeType = 'image/jpeg';
let quality = 0.85;
// --- 1. Apply Tool-Specific Settings ---
try {
if (this.activeTool === 'compress') {
quality = parseInt(document.getElementById('quality-slider').value) / 100;
mimeType = document.getElementById('compress-format').value;
// For compression, dimensions remain original
tempCanvas.width = this.originalImage.width;
tempCanvas.height = this.originalImage.height;
tempCtx.drawImage(this.originalImage, 0, 0);
} else if (this.activeTool === 'resize') {
targetWidth = parseInt(document.getElementById('resize-width').value) || 0;
targetHeight = parseInt(document.getElementById('resize-height').value) || 0;
// Maintain aspect ratio logic if one field is 0
if (targetWidth === 0 && targetHeight > 0) {
targetWidth = Math.round(targetHeight * (this.originalImage.width / this.originalImage.height));
} else if (targetHeight === 0 && targetWidth > 0) {
targetHeight = Math.round(targetWidth * (this.originalImage.height / this.originalImage.width));
} else if (targetWidth === 0 && targetHeight === 0) {
// If both are 0, use original dimensions
targetWidth = this.originalImage.width;
targetHeight = this.originalImage.height;
}
if (targetWidth <= 0 || targetHeight <= 0) {
throw new Error("Invalid resize dimensions.");
}
tempCanvas.width = targetWidth;
tempCanvas.height = targetHeight;
tempCtx.drawImage(this.originalImage, 0, 0, targetWidth, targetHeight);
mimeType = `image/${this.originalFile.type.split('/')[1] || 'png'}`; // Keep original type unless it's a resize-only operation
} else if (this.activeTool === 'convert') {
mimeType = document.getElementById('target-format').value;
// For conversion, dimensions remain original
tempCanvas.width = this.originalImage.width;
tempCanvas.height = this.originalImage.height;
tempCtx.drawImage(this.originalImage, 0, 0);
}
} catch (error) {
this.showLoading(false);
console.error("Processing Error:", error.message);
console.log(`User facing error: ${error.message} Please check your settings.`);
return;
}
// --- 2. Convert Canvas to Blob/URL and Update UI ---
tempCanvas.toBlob(async (blob) => {
if (!blob) {
this.showLoading(false);
console.error("Failed to create blob from canvas.");
return;
}
// Update main preview canvas to show the result
this.canvas.width = tempCanvas.width;
this.canvas.height = tempCanvas.height;
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.drawImage(tempCanvas, 0, 0);
// Update results panel
this.downloadBlob = blob;
this.downloadMimeType = mimeType;
// Use the original filename as the download name
this.downloadFileName = this.originalFile.name;
document.getElementById('new-size').textContent = `New Size: ${formatBytes(blob.size)}`;
document.getElementById('results-panel').classList.remove('hidden');
this.showLoading(false);
}, mimeType, quality);
},
// Function to reset the application state and go back to the drop zone
startNewImage() {
this.originalImage = null;
this.originalFile = null;
// Reset file input value to allow the same file to be selected again
document.getElementById('file-input').value = null;
// Hide processing area, results, and show drop zone
document.getElementById('processing-area').classList.add('hidden');
document.getElementById('drop-zone').classList.remove('hidden');
document.getElementById('results-panel').classList.add('hidden');
// Clear file info
document.getElementById('file-info').textContent = '';
document.getElementById('original-size').textContent = 'Original File Size: -';
document.getElementById('new-size').textContent = 'New Size: -';
// Optional: Clear canvas visually (though it will be hidden)
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
// NOTE: generateFileName is no longer used, but kept for context if needed later.
generateFileName(mimeType) {
const parts = this.originalFile.name.split('.');
const baseName = parts.slice(0, -1).join('.');
const extension = mimeType.split('/')[1].replace('jpeg', 'jpg');
return `${baseName}-clonimg.${extension}`;
},
downloadImage() {
if (!this.downloadBlob) return;
const url = URL.createObjectURL(this.downloadBlob);
const a = document.createElement('a');
a.href = url;
// Use the name stored during processing (which is the original file name)
a.download = this.downloadFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
// Initialize the app when the window loads
window.onload = () => {
ImageToolApp.init();
};
</script>
</body>
</html>