Spaces:
Running
Running
Download index.html from Examups/Image_Resizer: direct link, hf CLI and curl.
- Browser
- Download file 63.5 kB
-
https://huggingface.co/spaces/Examups/Image_Resizer/resolve/main/index.html
- Command line
-
hf download hf://spaces/Examups/Image_Resizer/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Examups/Image_Resizer/resolve/main/index.html
63.5 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Image Resizer Tool</title>
<style>
:root {
--primary-color: #3498db;
--primary-hover: #2980b9;
--success-color: #27ae60;
--success-hover: #219653;
--danger-color: #e74c3c;
--danger-hover: #c0392b;
--light-gray: #f5f5f5;
--medium-gray: #ddd;
--dark-gray: #7f8c8d;
--text-color: #2c3e50;
--white: #ffffff;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background-color: var(--light-gray);
color: var(--text-color);
line-height: 1.6;
}
h1 {
text-align: center;
color: var(--text-color);
margin-bottom: 30px;
}
.container {
background-color: var(--white);
border-radius: 10px;
padding: 25px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
.upload-area {
border: 3px dashed var(--primary-color);
border-radius: 8px;
padding: 40px;
text-align: center;
margin-bottom: 25px;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.upload-area:hover {
background-color: rgba(52, 152, 219, 0.05);
border-color: var(--primary-hover);
}
.upload-area.active {
background-color: rgba(52, 152, 219, 0.1);
}
.upload-area p {
margin: 0;
font-size: 18px;
color: var(--dark-gray);
}
.upload-area i {
font-size: 48px;
color: var(--primary-color);
margin-bottom: 15px;
display: block;
}
#fileInput {
display: none;
}
.controls {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 25px;
}
.control-group {
margin-bottom: 15px;
}
.control-group h3 {
margin-top: 0;
margin-bottom: 15px;
font-size: 18px;
border-bottom: 1px solid var(--medium-gray);
padding-bottom: 5px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: var(--text-color);
}
select, input, textarea {
width: 100%;
padding: 10px;
border: 1px solid var(--medium-gray);
border-radius: 6px;
font-size: 15px;
transition: border-color 0.3s;
}
select:focus, input:focus, textarea:focus {
outline: none;
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}
.btn {
display: inline-block;
color: white;
border: none;
padding: 12px 20px;
border-radius: 6px;
cursor: pointer;
font-size: 16px;
font-weight: 600;
transition: all 0.3s;
text-align: center;
text-decoration: none;
}
.btn-primary {
background-color: var(--primary-color);
}
.btn-primary:hover {
background-color: var(--primary-hover);
transform: translateY(-2px);
}
.btn-success {
background-color: var(--success-color);
}
.btn-success:hover {
background-color: var(--success-hover);
transform: translateY(-2px);
}
.btn-danger {
background-color: var(--danger-color);
}
.btn-danger:hover {
background-color: var(--danger-hover);
transform: translateY(-2px);
}
.btn-group {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.preview {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 25px;
margin-top: 30px;
}
.preview-item {
background-color: var(--white);
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.preview-item h3 {
margin-top: 0;
color: var(--text-color);
display: flex;
justify-content: space-between;
align-items: center;
}
.preview-img-container {
position: relative;
margin-bottom: 15px;
overflow: hidden;
border-radius: 6px;
}
.preview-img {
max-width: 100%;
height: auto;
display: block;
border-radius: 6px;
transition: transform 0.3s;
}
.preview-img-container:hover .preview-img {
transform: scale(1.03);
}
.dimensions {
font-size: 14px;
color: var(--dark-gray);
margin-top: 5px;
}
.loading {
display: none;
text-align: center;
margin: 30px 0;
}
.spinner {
border: 5px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top: 5px solid var(--primary-color);
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
margin: 0 auto 15px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.progress-container {
width: 100%;
background-color: #f1f1f1;
border-radius: 5px;
margin: 15px 0;
display: none;
}
.progress-bar {
height: 10px;
background-color: var(--primary-color);
border-radius: 5px;
width: 0%;
transition: width 0.3s;
}
.quality-slider {
width: 100%;
margin: 15px 0;
}
.preset-buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 15px;
}
.preset-btn {
padding: 5px 10px;
background-color: var(--light-gray);
border: 1px solid var(--medium-gray);
border-radius: 4px;
cursor: pointer;
font-size: 13px;
transition: all 0.2s;
}
.preset-btn:hover {
background-color: var(--medium-gray);
}
.preset-btn.active {
background-color: var(--primary-color);
color: white;
border-color: var(--primary-hover);
}
.tooltip {
position: relative;
display: inline-block;
margin-left: 5px;
cursor: help;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 200px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.3s;
font-size: 13px;
font-weight: normal;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
.advanced-options {
margin-top: 20px;
padding: 15px;
background-color: rgba(52, 152, 219, 0.05);
border-radius: 6px;
border-left: 4px solid var(--primary-color);
}
.toggle-advanced {
background: none;
border: none;
color: var(--primary-color);
cursor: pointer;
font-weight: 600;
display: flex;
align-items: center;
gap: 5px;
padding: 5px 0;
}
.toggle-advanced i {
transition: transform 0.3s;
}
.toggle-advanced.collapsed i {
transform: rotate(-90deg);
}
@media (max-width: 768px) {
.controls {
grid-template-columns: 1fr;
}
.preview {
grid-template-columns: 1fr;
}
.btn-group {
flex-direction: column;
}
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
<div class="container">
<h1><i class="fas fa-expand-alt"></i> Advanced Image Resizer Tool</h1>
<div class="upload-area" id="uploadArea">
<i class="fas fa-cloud-upload-alt"></i>
<p>Drag & drop your image here or click to browse</p>
<input type="file" id="fileInput" accept="image/*">
</div>
<div class="btn-group">
<button id="resizeBtn" class="btn btn-primary" disabled>
<i class="fas fa-crop-alt"></i> Resize Image
</button>
<button id="resetBtn" class="btn btn-danger" disabled>
<i class="fas fa-redo"></i> Reset
</button>
</div>
<div class="progress-container" id="progressContainer">
<div class="progress-bar" id="progressBar"></div>
</div>
<div class="loading" id="loading">
<div class="spinner"></div>
<p>Processing your image...</p>
</div>
<div class="controls">
<div class="control-group">
<h3><i class="fas fa-arrows-alt-h"></i> Dimensions</h3>
<label for="aspectRatio">Aspect Ratio:</label>
<select id="aspectRatio">
<option value="original">Original</option>
<option value="1:1">1:1 (Square)</option>
<option value="16:9">16:9 (Widescreen)</option>
<option value="4:3">4:3 (Standard)</option>
<option value="9:16">9:16 (Portrait)</option>
<option value="custom">Custom Ratio</option>
<option value="specific">Specific Dimensions</option>
</select>
<div id="customRatioGroup" style="display: none; margin-top: 10px;">
<label for="customRatio">Custom Ratio (width:height):</label>
<input type="text" id="customRatio" placeholder="e.g. 3:2">
</div>
<div id="specificDimensionsGroup" style="display: none; margin-top: 10px;">
<label for="specificWidth">Width (px):</label>
<input type="number" id="specificWidth" min="1" placeholder="Width">
<label for="specificHeight" style="margin-top: 10px;">Height (px):</label>
<input type="number" id="specificHeight" min="1" placeholder="Height">
<label style="margin-top: 10px; display: block;">
<input type="checkbox" id="lockAspect" checked>
Lock aspect ratio
</label>
</div>
<div class="preset-buttons" id="sizePresets">
<div class="preset-btn" data-width="1920" data-height="1080">HD (1920×1080)</div>
<div class="preset-btn" data-width="1280" data-height="720">HD (1280×720)</div>
<div class="preset-btn" data-width="1080" data-height="1080">Square (1080×1080)</div>
<div class="preset-btn" data-width="800" data-height="600">800×600</div>
<div class="preset-btn" data-width="640" data-height="480">640×480</div>
<div class="preset-btn" data-width="400" data-height="400">400×400</div>
</div>
</div>
<div class="control-group">
<h3><i class="fas fa-sliders-h"></i> Resize Options</h3>
<label for="resizeMethod">Resize Method:</label>
<select id="resizeMethod">
<option value="cover">Cover (Crop to fit)</option>
<option value="contain">Contain (Fit inside, add padding)</option>
<option value="stretch">Stretch (Distort to fit)</option>
<option value="fill">Fill (Extend edges)</option>
</select>
<label for="backgroundColor" style="margin-top: 15px;">Background Color:</label>
<input type="color" id="backgroundColor" value="#ffffff">
<label for="imageQuality" style="margin-top: 15px;">Image Quality (JPEG):</label>
<input type="range" id="imageQuality" min="10" max="100" value="85" class="quality-slider">
<div style="display: flex; justify-content: space-between;">
<span>10%</span>
<span id="qualityValue">85%</span>
<span>100%</span>
</div>
<label for="outputFormat" style="margin-top: 15px;">Output Format:</label>
<select id="outputFormat">
<option value="original">Original Format</option>
<option value="png">PNG (Lossless)</option>
<option value="jpeg">JPEG (Compressed)</option>
<option value="webp">WebP (Modern)</option>
</select>
</div>
<div class="control-group">
<h3><i class="fas fa-magic"></i> Enhancements</h3>
<label for="brightness">Brightness:</label>
<input type="range" id="brightness" min="-100" max="100" value="0" class="quality-slider">
<label for="contrast" style="margin-top: 15px;">Contrast:</label>
<input type="range" id="contrast" min="-100" max="100" value="0" class="quality-slider">
<label for="saturation" style="margin-top: 15px;">Saturation:</label>
<input type="range" id="saturation" min="-100" max="100" value="0" class="quality-slider">
<label for="sharpness" style="margin-top: 15px;">Sharpness:</label>
<input type="range" id="sharpness" min="0" max="100" value="0" class="quality-slider">
<label for="rotation" style="margin-top: 15px;">Rotation:</label>
<select id="rotation">
<option value="0">0°</option>
<option value="90">90°</option>
<option value="180">180°</option>
<option value="270">270°</option>
<option value="custom">Custom Angle</option>
</select>
<div id="customRotationGroup" style="display: none; margin-top: 10px;">
<label for="customRotation">Custom Rotation Angle (degrees):</label>
<input type="number" id="customRotation" min="-360" max="360" value="0">
</div>
</div>
</div>
<button class="toggle-advanced" id="toggleAdvanced">
<i class="fas fa-chevron-down"></i> Advanced Options
</button>
<div class="advanced-options" id="advancedOptions">
<div class="control-group">
<label for="blurRadius">Blur Radius:</label>
<input type="range" id="blurRadius" min="0" max="20" value="0" class="quality-slider">
<label for="grayscale" style="margin-top: 15px;">
<input type="checkbox" id="grayscale"> Convert to Grayscale
</label>
<label for="sepia" style="margin-top: 15px;">
<input type="checkbox" id="sepia"> Apply Sepia Effect
</label>
<label for="invert" style="margin-top: 15px;">
<input type="checkbox" id="invert"> Invert Colors
</label>
<label for="border" style="margin-top: 15px;">
<input type="checkbox" id="addBorder"> Add Border
</label>
<div id="borderOptions" style="display: none; margin-top: 10px;">
<label for="borderColor">Border Color:</label>
<input type="color" id="borderColor" value="#000000">
<label for="borderWidth" style="margin-top: 10px;">Border Width (px):</label>
<input type="number" id="borderWidth" min="1" value="5">
<label for="borderType" style="margin-top: 10px;">Border Type:</label>
<select id="borderType">
<option value="solid">Solid</option>
<option value="dashed">Dashed</option>
<option value="dotted">Dotted</option>
</select>
</div>
<label for="watermark" style="margin-top: 15px;">
<input type="checkbox" id="addWatermark"> Add Watermark
</label>
<div id="watermarkOptions" style="display: none; margin-top: 10px;">
<label for="watermarkText">Watermark Text:</label>
<input type="text" id="watermarkText" placeholder="Your watermark text">
<label for="watermarkColor" style="margin-top: 10px;">Text Color:</label>
<input type="color" id="watermarkColor" value="#ffffff">
<label for="watermarkOpacity" style="margin-top: 10px;">Opacity:</label>
<input type="range" id="watermarkOpacity" min="10" max="100" value="50" class="quality-slider">
<label for="watermarkPosition" style="margin-top: 10px;">Position:</label>
<select id="watermarkPosition">
<option value="bottom-right">Bottom Right</option>
<option value="bottom-left">Bottom Left</option>
<option value="top-right">Top Right</option>
<option value="top-left">Top Left</option>
<option value="center">Center</option>
</select>
<label for="watermarkSize" style="margin-top: 10px;">Size:</label>
<select id="watermarkSize">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select>
</div>
</div>
</div>
<div class="preview" id="previewContainer" style="display: none;">
<div class="preview-item">
<h3>Original Image <span class="dimensions" id="originalDimensions"></span></h3>
<div class="preview-img-container">
<img id="originalPreview" class="preview-img">
</div>
</div>
<div class="preview-item">
<h3>Resized Image <span class="dimensions" id="resizedDimensions"></span></h3>
<div class="preview-img-container">
<img id="resizedPreview" class="preview-img">
</div>
<div style="display: flex; gap: 10px; margin-top: 15px;">
<a href="#" id="downloadBtn" class="btn btn-success">
<i class="fas fa-download"></i> Download
</a>
<button id="copyBtn" class="btn btn-primary">
<i class="fas fa-copy"></i> Copy to Clipboard
</button>
</div>
<div id="fileSizeInfo" style="margin-top: 10px; font-size: 14px; color: var(--dark-gray);"></div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const fileInput = document.getElementById('fileInput');
const uploadArea = document.getElementById('uploadArea');
const aspectRatioSelect = document.getElementById('aspectRatio');
const customRatioGroup = document.getElementById('customRatioGroup');
const customRatioInput = document.getElementById('customRatio');
const specificDimensionsGroup = document.getElementById('specificDimensionsGroup');
const specificWidthInput = document.getElementById('specificWidth');
const specificHeightInput = document.getElementById('specificHeight');
const lockAspectCheckbox = document.getElementById('lockAspect');
const resizeMethodSelect = document.getElementById('resizeMethod');
const backgroundColorInput = document.getElementById('backgroundColor');
const outputFormatSelect = document.getElementById('outputFormat');
const imageQualityInput = document.getElementById('imageQuality');
const qualityValue = document.getElementById('qualityValue');
const brightnessInput = document.getElementById('brightness');
const contrastInput = document.getElementById('contrast');
const saturationInput = document.getElementById('saturation');
const sharpnessInput = document.getElementById('sharpness');
const rotationSelect = document.getElementById('rotation');
const customRotationGroup = document.getElementById('customRotationGroup');
const customRotationInput = document.getElementById('customRotation');
const blurRadiusInput = document.getElementById('blurRadius');
const grayscaleCheckbox = document.getElementById('grayscale');
const sepiaCheckbox = document.getElementById('sepia');
const invertCheckbox = document.getElementById('invert');
const addBorderCheckbox = document.getElementById('addBorder');
const borderOptions = document.getElementById('borderOptions');
const borderColorInput = document.getElementById('borderColor');
const borderWidthInput = document.getElementById('borderWidth');
const borderTypeSelect = document.getElementById('borderType');
const addWatermarkCheckbox = document.getElementById('addWatermark');
const watermarkOptions = document.getElementById('watermarkOptions');
const watermarkTextInput = document.getElementById('watermarkText');
const watermarkColorInput = document.getElementById('watermarkColor');
const watermarkOpacityInput = document.getElementById('watermarkOpacity');
const watermarkPositionSelect = document.getElementById('watermarkPosition');
const watermarkSizeSelect = document.getElementById('watermarkSize');
const resizeBtn = document.getElementById('resizeBtn');
const resetBtn = document.getElementById('resetBtn');
const loadingDiv = document.getElementById('loading');
const progressContainer = document.getElementById('progressContainer');
const progressBar = document.getElementById('progressBar');
const previewContainer = document.getElementById('previewContainer');
const originalPreview = document.getElementById('originalPreview');
const resizedPreview = document.getElementById('resizedPreview');
const originalDimensions = document.getElementById('originalDimensions');
const resizedDimensions = document.getElementById('resizedDimensions');
const downloadBtn = document.getElementById('downloadBtn');
const copyBtn = document.getElementById('copyBtn');
const fileSizeInfo = document.getElementById('fileSizeInfo');
const sizePresets = document.getElementById('sizePresets');
const toggleAdvancedBtn = document.getElementById('toggleAdvanced');
const advancedOptions = document.getElementById('advancedOptions');
// Variables
let originalImage = null;
let originalWidth = 0;
let originalHeight = 0;
let originalAspectRatio = 0;
let processing = false;
// Event Listeners
fileInput.addEventListener('change', handleFileSelect);
uploadArea.addEventListener('click', () => fileInput.click());
uploadArea.addEventListener('dragover', handleDragOver);
uploadArea.addEventListener('dragleave', handleDragLeave);
uploadArea.addEventListener('drop', handleDrop);
aspectRatioSelect.addEventListener('change', handleAspectRatioChange);
customRatioInput.addEventListener('input', validateCustomRatio);
specificWidthInput.addEventListener('input', handleSpecificDimensionChange);
specificHeightInput.addEventListener('input', handleSpecificDimensionChange);
lockAspectCheckbox.addEventListener('change', handleLockAspectChange);
imageQualityInput.addEventListener('input', updateQualityValue);
rotationSelect.addEventListener('change', handleRotationChange);
addBorderCheckbox.addEventListener('change', toggleBorderOptions);
addWatermarkCheckbox.addEventListener('change', toggleWatermarkOptions);
resizeBtn.addEventListener('click', resizeImage);
resetBtn.addEventListener('click', resetTool);
downloadBtn.addEventListener('click', downloadImage);
copyBtn.addEventListener('click', copyToClipboard);
sizePresets.addEventListener('click', handlePresetClick);
toggleAdvancedBtn.addEventListener('click', toggleAdvancedOptions);
// Initialize
updateQualityValue();
toggleAdvancedBtn.classList.add('collapsed');
advancedOptions.style.display = 'none';
// Functions
function handleFileSelect(e) {
const file = e.target.files ? e.target.files[0] : e.dataTransfer.files[0];
if (!file.type.match('image.*')) {
alert('Please select an image file (JPEG, PNG, GIF, etc.)');
return;
}
// Show loading state
loadingDiv.style.display = 'block';
progressContainer.style.display = 'block';
progressBar.style.width = '0%';
uploadArea.classList.add('active');
const reader = new FileReader();
reader.onloadstart = function() {
progressBar.style.width = '10%';
};
reader.onprogress = function(e) {
if (e.lengthComputable) {
const percentLoaded = Math.round((e.loaded / e.total) * 90);
progressBar.style.width = `${10 + percentLoaded}%`;
}
};
reader.onload = function(e) {
progressBar.style.width = '100%';
originalImage = new Image();
originalImage.onload = function() {
originalWidth = originalImage.width;
originalHeight = originalImage.height;
originalAspectRatio = originalWidth / originalHeight;
originalPreview.src = e.target.result;
originalDimensions.textContent = `${originalWidth} × ${originalHeight} (${calculateAspectRatio(originalWidth, originalHeight)})`;
// Enable controls
resizeBtn.disabled = false;
resetBtn.disabled = false;
// Show preview
previewContainer.style.display = 'grid';
// Hide loading
setTimeout(() => {
loadingDiv.style.display = 'none';
progressContainer.style.display = 'none';
uploadArea.classList.remove('active');
}, 500);
// Auto-resize if needed
if (aspectRatioSelect.value !== 'original') {
setTimeout(resizeImage, 100);
}
};
originalImage.src = e.target.result;
};
reader.onerror = function() {
alert('Error reading file. Please try again.');
loadingDiv.style.display = 'none';
progressContainer.style.display = 'none';
uploadArea.classList.remove('active');
};
reader.readAsDataURL(file);
}
function handleDragOver(e) {
e.preventDefault();
uploadArea.style.backgroundColor = 'rgba(52, 152, 219, 0.1)';
uploadArea.style.borderColor = 'var(--primary-hover)';
}
function handleDragLeave() {
uploadArea.style.backgroundColor = '';
uploadArea.style.borderColor = 'var(--primary-color)';
}
function handleDrop(e) {
e.preventDefault();
uploadArea.style.backgroundColor = '';
uploadArea.style.borderColor = 'var(--primary-color)';
if (e.dataTransfer.files.length) {
fileInput.files = e.dataTransfer.files;
handleFileSelect(e);
}
}
function handleAspectRatioChange() {
const value = aspectRatioSelect.value;
customRatioGroup.style.display = value === 'custom' ? 'block' : 'none';
specificDimensionsGroup.style.display = value === 'specific' ? 'block' : 'none';
if (value === 'specific' && originalImage) {
specificWidthInput.value = originalWidth;
specificHeightInput.value = originalHeight;
}
if (originalImage) {
resizeImage();
}
}
function validateCustomRatio() {
const parts = customRatioInput.value.split(':');
if (parts.length !== 2 || isNaN(parts[0]) || isNaN(parts[1]) || parts[0] <= 0 || parts[1] <= 0) {
customRatioInput.style.borderColor = 'var(--danger-color)';
return false;
} else {
customRatioInput.style.borderColor = '';
return true;
}
}
function handleSpecificDimensionChange(e) {
if (!lockAspectCheckbox.checked || !originalImage) return;
const changedInput = e.target.id;
if (changedInput === 'specificWidth') {
specificHeightInput.value = Math.round(specificWidthInput.value / originalAspectRatio);
} else {
specificWidthInput.value = Math.round(specificHeightInput.value * originalAspectRatio);
}
}
function handleLockAspectChange() {
if (lockAspectCheckbox.checked && originalImage) {
specificHeightInput.value = Math.round(specificWidthInput.value / originalAspectRatio);
}
}
function updateQualityValue() {
qualityValue.textContent = `${imageQualityInput.value}%`;
}
function handleRotationChange() {
customRotationGroup.style.display = rotationSelect.value === 'custom' ? 'block' : 'none';
}
function toggleBorderOptions() {
borderOptions.style.display = addBorderCheckbox.checked ? 'block' : 'none';
}
function toggleWatermarkOptions() {
watermarkOptions.style.display = addWatermarkCheckbox.checked ? 'block' : 'none';
}
function toggleAdvancedOptions() {
const isCollapsed = toggleAdvancedBtn.classList.contains('collapsed');
if (isCollapsed) {
toggleAdvancedBtn.classList.remove('collapsed');
advancedOptions.style.display = 'block';
} else {
toggleAdvancedBtn.classList.add('collapsed');
advancedOptions.style.display = 'none';
}
}
function handlePresetClick(e) {
if (e.target.classList.contains('preset-btn')) {
// Remove active class from all buttons
document.querySelectorAll('.preset-btn').forEach(btn => {
btn.classList.remove('active');
});
// Add active class to clicked button
e.target.classList.add('active');
// Set aspect ratio to specific dimensions
aspectRatioSelect.value = 'specific';
specificDimensionsGroup.style.display = 'block';
// Set the dimensions
const width = parseInt(e.target.dataset.width);
const height = parseInt(e.target.dataset.height);
specificWidthInput.value = width;
specificHeightInput.value = height;
// Update lock aspect ratio
lockAspectCheckbox.checked = false;
// Trigger resize if image is loaded
if (originalImage) {
resizeImage();
}
}
}
function calculateAspectRatio(width, height) {
const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
const divisor = gcd(width, height);
return `${width / divisor}:${height / divisor}`;
}
function parseAspectRatio(ratioStr) {
if (ratioStr === 'custom') {
if (!validateCustomRatio()) return null;
const parts = customRatioInput.value.split(':');
return {
width: parseFloat(parts[0]),
height: parseFloat(parts[1])
};
} else if (ratioStr === 'specific') {
return {
width: parseInt(specificWidthInput.value) || originalWidth,
height: parseInt(specificHeightInput.value) || originalHeight
};
} else if (ratioStr === 'original') {
return {
width: originalWidth,
height: originalHeight
};
} else {
const parts = ratioStr.split(':');
return {
width: parseFloat(parts[0]),
height: parseFloat(parts[1])
};
}
}
function resizeImage() {
if (!originalImage || processing) return;
processing = true;
loadingDiv.style.display = 'block';
previewContainer.style.display = 'none';
// Use setTimeout to allow UI to update
setTimeout(() => {
try {
const targetRatio = parseAspectRatio(aspectRatioSelect.value);
if (!targetRatio) {
processing = false;
loadingDiv.style.display = 'none';
return;
}
const method = resizeMethodSelect.value;
const bgColor = backgroundColorInput.value;
const quality = parseInt(imageQualityInput.value) / 100;
const outputFormat = outputFormatSelect.value === 'original'
? getFileExtension(fileInput.files[0].name)
: outputFormatSelect.value;
// Create canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Calculate dimensions based on method
let drawWidth, drawHeight, offsetX = 0, offsetY = 0;
let canvasWidth = targetRatio.width;
let canvasHeight = targetRatio.height;
// Apply rotation if needed
let rotationAngle = 0;
if (rotationSelect.value === 'custom') {
rotationAngle = parseInt(customRotationInput.value) || 0;
} else {
rotationAngle = parseInt(rotationSelect.value) || 0;
}
// Swap dimensions for 90° and 270° rotations
if (Math.abs(rotationAngle) % 180 === 90) {
[canvasWidth, canvasHeight] = [canvasHeight, canvasWidth];
}
// Scale dimensions to maintain reasonable size
const maxDimension = 2000;
const scaleFactor = Math.min(
maxDimension / canvasWidth,
maxDimension / canvasHeight
);
canvas.width = Math.round(canvasWidth * scaleFactor);
canvas.height = Math.round(canvasHeight * scaleFactor);
// Apply background color
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Calculate drawing parameters based on resize method
if (method === 'cover') {
// Crop to cover the target aspect ratio
const sourceAspect = originalImage.width / originalImage.height;
const targetAspect = targetRatio.width / targetRatio.height;
let sourceX = 0, sourceY = 0;
let sourceWidth = originalImage.width;
let sourceHeight = originalImage.height;
if (sourceAspect > targetAspect) {
// Original is wider than target - crop sides
sourceWidth = originalImage.height * targetAspect;
sourceX = (originalImage.width - sourceWidth) / 2;
} else {
// Original is taller than target - crop top/bottom
sourceHeight = originalImage.width / targetAspect;
sourceY = (originalImage.height - sourceHeight) / 2;
}
// Draw the cropped portion of the original image, scaled to target size
ctx.drawImage(
originalImage,
sourceX, sourceY, sourceWidth, sourceHeight,
0, 0, canvas.width, canvas.height
);
}
else if (method === 'contain') {
// Fit inside target aspect ratio with padding
const sourceAspect = originalImage.width / originalImage.height;
const targetAspect = targetRatio.width / targetRatio.height;
if (sourceAspect > targetAspect) {
// Original is wider than target - add padding top/bottom
drawWidth = canvas.width;
drawHeight = canvas.width / sourceAspect;
offsetY = (canvas.height - drawHeight) / 2;
} else {
// Original is taller than target - add padding sides
drawWidth = canvas.height * sourceAspect;
drawHeight = canvas.height;
offsetX = (canvas.width - drawWidth) / 2;
}
// Draw the original image centered with padding
ctx.drawImage(
originalImage,
offsetX, offsetY, drawWidth, drawHeight
);
}
else if (method === 'stretch') {
// Stretch to fit target aspect ratio (distorts image)
ctx.drawImage(
originalImage,
0, 0, canvas.width, canvas.height
);
}
else if (method === 'fill') {
// Fill by extending edges
// This is a simplified version - more advanced algorithms exist
ctx.drawImage(
originalImage,
0, 0, canvas.width, canvas.height
);
}
// Apply image enhancements
applyImageEffects(ctx, canvas.width, canvas.height);
// Rotate the image if needed
if (rotationAngle !== 0) {
rotateImage(canvas, rotationAngle);
}
// Add border if enabled
if (addBorderCheckbox.checked) {
addBorderToCanvas(canvas, ctx);
}
// Add watermark if enabled
if (addWatermarkCheckbox.checked && watermarkTextInput.value) {
addWatermarkToCanvas(canvas, ctx);
}
// Get the final image data
let mimeType;
switch (outputFormat) {
case 'png': mimeType = 'image/png'; break;
case 'jpeg': mimeType = 'image/jpeg'; break;
case 'webp': mimeType = 'image/webp'; break;
default: mimeType = fileInput.files[0].type || 'image/png';
}
const imageData = canvas.toDataURL(mimeType, outputFormat === 'jpeg' ? quality : 1);
// Update the preview
resizedPreview.src = imageData;
resizedDimensions.textContent = `${canvas.width} × ${canvas.height} (${calculateAspectRatio(canvas.width, canvas.height)})`;
// Update download button
downloadBtn.href = imageData;
const extension = outputFormat === 'jpeg' ? 'jpg' : outputFormat;
downloadBtn.download = `resized-${fileInput.files[0].name.replace(/\.[^/.]+$/, "")}.${extension}`;
// Update file size info
updateFileSizeInfo(imageData);
// Show preview
previewContainer.style.display = 'grid';
} catch (error) {
console.error('Error resizing image:', error);
alert('An error occurred while processing the image. Please try again.');
} finally {
loadingDiv.style.display = 'none';
processing = false;
}
}, 100);
}
function applyImageEffects(ctx, width, height) {
// Create a temporary canvas for effects
const tempCanvas = document.createElement('canvas');
tempCanvas.width = width;
tempCanvas.height = height;
const tempCtx = tempCanvas.getContext('2d');
// Draw the current canvas content to temp canvas
tempCtx.drawImage(ctx.canvas, 0, 0);
// Get image data
const imageData = tempCtx.getImageData(0, 0, width, height);
const data = imageData.data;
// Apply brightness, contrast, saturation
const brightness = parseInt(brightnessInput.value) / 100;
const contrast = parseInt(contrastInput.value) / 100;
const saturation = parseInt(saturationInput.value) / 100;
const grayscale = grayscaleCheckbox.checked;
const sepia = sepiaCheckbox.checked;
const invert = invertCheckbox.checked;
const sharpness = parseInt(sharpnessInput.value) / 100;
const blurRadius = parseInt(blurRadiusInput.value);
// Apply pixel-level effects
if (brightness !== 0 || contrast !== 0 || saturation !== 0 || grayscale || sepia || invert) {
for (let i = 0; i < data.length; i += 4) {
let r = data[i];
let g = data[i + 1];
let b = data[i + 2];
// Apply brightness
if (brightness !== 0) {
r = r + (255 * brightness);
g = g + (255 * brightness);
b = b + (255 * brightness);
}
// Apply contrast
if (contrast !== 0) {
const factor = (259 * (contrast + 255)) / (255 * (259 - contrast));
r = factor * (r - 128) + 128;
g = factor * (g - 128) + 128;
b = factor * (b - 128) + 128;
}
// Apply saturation
if (saturation !== 0) {
const gray = 0.2989 * r + 0.5870 * g + 0.1140 * b;
r = gray + saturation * (r - gray);
g = gray + saturation * (g - gray);
b = gray + saturation * (b - gray);
}
// Apply grayscale
if (grayscale) {
const avg = 0.299 * r + 0.587 * g + 0.114 * b;
r = g = b = avg;
}
// Apply sepia
if (sepia) {
r = Math.min(255, (r * 0.393) + (g * 0.769) + (b * 0.189));
g = Math.min(255, (r * 0.349) + (g * 0.686) + (b * 0.168));
b = Math.min(255, (r * 0.272) + (g * 0.534) + (b * 0.131));
}
// Apply invert
if (invert) {
r = 255 - r;
g = 255 - g;
b = 255 - b;
}
// Clamp values
data[i] = Math.max(0, Math.min(255, r));
data[i + 1] = Math.max(0, Math.min(255, g));
data[i + 2] = Math.max(0, Math.min(255, b));
}
tempCtx.putImageData(imageData, 0, 0);
}
// Apply blur (simplified - for better blur use more advanced methods)
if (blurRadius > 0) {
tempCtx.filter = `blur(${blurRadius}px)`;
tempCtx.drawImage(tempCanvas, 0, 0);
tempCtx.filter = 'none';
}
// Apply sharpness (simplified unsharp mask)
if (sharpness > 0) {
// Create a blurred version
const blurCanvas = document.createElement('canvas');
blurCanvas.width = width;
blurCanvas.height = height;
const blurCtx = blurCanvas.getContext('2d');
blurCtx.filter = 'blur(1px)';
blurCtx.drawImage(tempCanvas, 0, 0);
blurCtx.filter = 'none';
// Subtract blurred from original and add back with strength
const amount = sharpness * 2;
tempCtx.globalCompositeOperation = 'overlay';
tempCtx.globalAlpha = amount;
tempCtx.drawImage(blurCanvas, 0, 0);
tempCtx.globalCompositeOperation = 'source-over';
tempCtx.globalAlpha = 1.0;
}
// Draw the final result back to main canvas
ctx.drawImage(tempCanvas, 0, 0);
}
function rotateImage(canvas, angle) {
angle = angle % 360;
if (angle === 0) return;
const radians = angle * Math.PI / 180;
const sin = Math.abs(Math.sin(radians));
const cos = Math.abs(Math.cos(radians));
const newWidth = Math.floor(canvas.width * cos + canvas.height * sin);
const newHeight = Math.floor(canvas.width * sin + canvas.height * cos);
const tempCanvas = document.createElement('canvas');
tempCanvas.width = newWidth;
tempCanvas.height = newHeight;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.translate(newWidth / 2, newHeight / 2);
tempCtx.rotate(radians);
tempCtx.drawImage(canvas, -canvas.width / 2, -canvas.height / 2);
// Resize the original canvas
canvas.width = newWidth;
canvas.height = newHeight;
// Draw the rotated image back
const ctx = canvas.getContext('2d');
ctx.drawImage(tempCanvas, 0, 0);
}
function addBorderToCanvas(canvas, ctx) {
const borderWidth = parseInt(borderWidthInput.value) || 5;
const borderColor = borderColorInput.value;
const borderType = borderTypeSelect.value;
// Save the current image
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Clear canvas and draw border
ctx.fillStyle = borderColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the image inside the border
const innerWidth = canvas.width - (borderWidth * 2);
const innerHeight = canvas.height - (borderWidth * 2);
if (borderType === 'dashed' || borderType === 'dotted') {
// For dashed/dotted borders, we need to draw the image first
ctx.putImageData(imageData, borderWidth, borderWidth, 0, 0, innerWidth, innerHeight);
// Then draw the border on top
ctx.strokeStyle = borderColor;
ctx.lineWidth = borderWidth;
if (borderType === 'dashed') {
ctx.setLineDash([10, 5]);
} else {
ctx.setLineDash([2, 3]);
}
ctx.strokeRect(borderWidth / 2, borderWidth / 2,
canvas.width - borderWidth, canvas.height - borderWidth);
ctx.setLineDash([]);
} else {
// For solid border, just draw the image inside
ctx.putImageData(imageData, borderWidth, borderWidth, 0, 0, innerWidth, innerHeight);
}
}
function addWatermarkToCanvas(canvas, ctx) {
const text = watermarkTextInput.value || '';
const color = watermarkColorInput.value;
const opacity = parseInt(watermarkOpacityInput.value) / 100;
const position = watermarkPositionSelect.value;
const size = watermarkSizeSelect.value;
if (!text) return;
// Set font size based on selection
let fontSize;
switch (size) {
case 'small': fontSize = canvas.width / 20; break;
case 'large': fontSize = canvas.width / 10; break;
default: fontSize = canvas.width / 15; // medium
}
ctx.font = `bold ${fontSize}px Arial`;
ctx.fillStyle = color;
ctx.globalAlpha = opacity;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Calculate position
let x, y;
const padding = canvas.width / 20;
switch (position) {
case 'top-left':
x = padding + ctx.measureText(text).width / 2;
y = padding + fontSize / 2;
ctx.textAlign = 'left';
break;
case 'top-right':
x = canvas.width - padding - ctx.measureText(text).width / 2;
y = padding + fontSize / 2;
ctx.textAlign = 'right';
break;
case 'bottom-left':
x = padding + ctx.measureText(text).width / 2;
y = canvas.height - padding - fontSize / 2;
ctx.textAlign = 'left';
break;
case 'bottom-right':
x = canvas.width - padding - ctx.measureText(text).width / 2;
y = canvas.height - padding - fontSize / 2;
ctx.textAlign = 'right';
break;
default: // center
x = canvas.width / 2;
y = canvas.height / 2;
}
// Add text shadow for better visibility
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 5;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
// Draw the text
ctx.fillText(text, x, y);
// Reset context settings
ctx.globalAlpha = 1.0;
ctx.shadowColor = 'transparent';
}
function updateFileSizeInfo(dataURL) {
// Calculate the approximate file size
const sizeInBytes = Math.round((dataURL.length * 3) / 4);
let sizeText;
if (sizeInBytes < 1024) {
sizeText = `${sizeInBytes} bytes`;
} else if (sizeInBytes < 1024 * 1024) {
sizeText = `${(sizeInBytes / 1024).toFixed(1)} KB`;
} else {
sizeText = `${(sizeInBytes / (1024 * 1024)).toFixed(1)} MB`;
}
fileSizeInfo.textContent = `File size: ~${sizeText}`;
}
function getFileExtension(filename) {
return filename.split('.').pop().toLowerCase();
}
function downloadImage(e) {
if (!resizedPreview.src) {
e.preventDefault();
alert('No resized image available to download.');
}
// The actual download is handled by the anchor tag's download attribute
}
async function copyToClipboard() {
if (!resizedPreview.src) {
alert('No resized image available to copy.');
return;
}
try {
// Fetch the image data
const response = await fetch(resizedPreview.src);
const blob = await response.blob();
// Copy to clipboard
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
alert('Image copied to clipboard!');
} catch (error) {
console.error('Error copying image:', error);
alert('Failed to copy image to clipboard. Your browser may not support this feature.');
}
}
function resetTool() {
// Reset file input
fileInput.value = '';
// Reset previews
originalPreview.src = '';
resizedPreview.src = '';
originalDimensions.textContent = '';
resizedDimensions.textContent = '';
fileSizeInfo.textContent = '';
// Hide preview container
previewContainer.style.display = 'none';
// Reset controls
aspectRatioSelect.value = 'original';
customRatioGroup.style.display = 'none';
specificDimensionsGroup.style.display = 'none';
resizeMethodSelect.value = 'cover';
backgroundColorInput.value = '#ffffff';
outputFormatSelect.value = 'original';
imageQualityInput.value = '85';
updateQualityValue();
brightnessInput.value = '0';
contrastInput.value = '0';
saturationInput.value = '0';
sharpnessInput.value = '0';
rotationSelect.value = '0';
customRotationGroup.style.display = 'none';
blurRadiusInput.value = '0';
grayscaleCheckbox.checked = false;
sepiaCheckbox.checked = false;
invertCheckbox.checked = false;
addBorderCheckbox.checked = false;
borderOptions.style.display = 'none';
addWatermarkCheckbox.checked = false;
watermarkOptions.style.display = 'none';
// Disable buttons
resizeBtn.disabled = true;
resetBtn.disabled = true;
// Reset variables
originalImage = null;
originalWidth = 0;
originalHeight = 0;
originalAspectRatio = 0;
// Remove active class from preset buttons
document.querySelectorAll('.preset-btn').forEach(btn => {
btn.classList.remove('active');
});
}
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Image Resizer Tool</title>
<style>
:root {
--primary-color: #3498db;
--primary-hover: #2980b9;
--success-color: #27ae60;
--success-hover: #219653;
--danger-color: #e74c3c;
--danger-hover: #c0392b;
--light-gray: #f5f5f5;
--medium-gray: #ddd;
--dark-gray: #7f8c8d;
--text-color: #2c3e50;
--white: #ffffff;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background-color: var(--light-gray);
color: var(--text-color);
line-height: 1.6;
}
h1 {
text-align: center;
color: var(--text-color);
margin-bottom: 30px;
}
.container {
background-color: var(--white);
border-radius: 10px;
padding: 25px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
.upload-area {
border: 3px dashed var(--primary-color);
border-radius: 8px;
padding: 40px;
text-align: center;
margin-bottom: 25px;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.upload-area:hover {
background-color: rgba(52, 152, 219, 0.05);
border-color: var(--primary-hover);
}
.upload-area.active {
background-color: rgba(52, 152, 219, 0.1);
}
.upload-area p {
margin: 0;
font-size: 18px;
color: var(--dark-gray);
}
.upload-area i {
font-size: 48px;
color: var(--primary-color);
margin-bottom: 15px;
display: block;
}
#fileInput {
display: none;
}
.controls {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 25px;
}
.control-group {
margin-bottom: 15px;
}
.control-group h3 {
margin-top: 0;
margin-bottom: 15px;
font-size: 18px;
border-bottom: 1px solid var(--medium-gray);
padding-bottom: 5px;