↩️
Назад
Категории
Все категории
1С
2040
AD
CG
IOT умный дом
Joomla
Linux
macOS
mysql
php
SEO
Windows
Безопасность
Железо
Защита данных
Простотак
Сети LAN
Создание сайтов
Электрика
Электроника
Java-script уменьшения картинки по кнопке
24.01.2026 | коды из категории: Создание сайтов
Уменьшить изображения
Уменьшить на:
25%
50%
75%
90%
Свой размер...
Уменьшить все изображения
Выбранные файлы:
Нет выбранных файлов
Это мини-инструмент прямо в браузере, который позволяет уменьшить размер изображения без программ и без загрузки на сервер.
Ты выбираешь картинку → указываешь, на сколько процентов её уменьшить (например, до 50% от оригинала) → нажимаешь кнопку → скачиваешь готовый файл.
Всё происходит локально: твоё изображение никогда не уходит в интернет — оно обрабатывается только в памяти браузера. Это быстро, безопасно и удобно для блога.
В админку не лезит картинка, быстро уменьшить без программ.
<div style="max-width: 800px; margin: 20px auto; font-family: sans-serif; padding: 20px;">
<h3>Уменьшить изображения</h3>
<div style="margin-bottom: 20px;">
<input type="file" id="imageUpload" accept="image/*" multiple />
<div style="font-size: 12px; color: #666; margin-top: 5px;">
Выберите несколько файлов (Ctrl+клик или Shift+клик)
</div>
</div>
<div style="margin-bottom: 20px;">
<label>Уменьшить на:
<select id="scalePercent">
<option value="75">25%</option>
<option value="50" selected>50%</option>
<option value="25">75%</option>
<option value="10">90%</option>
<option value="custom">Свой размер...</option>
</select>
</label>
<div id="customSizeContainer" style="display: none; margin-top: 10px;">
<label>Ширина (px): <input type="number" id="customWidth" min="1" value="800"></label>
<label style="margin-left: 10px;">Высота (px): <input type="number" id="customHeight" min="1" value="600"></label>
<div style="font-size: 12px; color: #666;">
Если задать только одну размерность, вторая рассчитается пропорционально
</div>
</div>
</div>
<div style="margin-bottom: 20px;">
<label>Формат вывода:
<select id="format">
<option value="jpeg">JPEG</option>
<option value="png">PNG</option>
<option value="webp">WebP</option>
</select>
</label>
<div id="qualityContainer" style="margin-top: 10px;">
<label>Качество (для JPEG/WebP):
<input type="range" id="quality" min="0.1" max="1" step="0.1" value="0.85">
<span id="qualityValue">85%</span>
</label>
</div>
</div>
<button onclick="processImages()" style="padding: 10px 20px; font-size: 16px;">
Уменьшить все изображения
</button>
<div id="progressContainer" style="display: none; margin-top: 20px;">
<div id="progressBar" style="width: 100%; height: 20px; background-color: #f0f0f0; border-radius: 10px; overflow: hidden;">
<div id="progressFill" style="width: 0%; height: 100%; background-color: #4CAF50; transition: width 0.3s;"></div>
</div>
<div id="progressText" style="text-align: center; margin-top: 5px;">Обработано: 0/0</div>
</div>
<div id="fileList" style="margin-top: 20px; border-top: 1px solid #ddd; padding-top: 15px;">
<h4>Выбранные файлы:</h4>
<div id="fileNames">Нет выбранных файлов</div>
</div>
<canvas id="previewCanvas" style="display:none;"></canvas>
</div>
<script>
// Показываем/скрываем поля для кастомного размера
document.getElementById('scalePercent').addEventListener('change', function() {
const customContainer = document.getElementById('customSizeContainer');
customContainer.style.display = this.value === 'custom' ? 'block' : 'none';
});
// Обновляем значение качества
document.getElementById('quality').addEventListener('input', function() {
document.getElementById('qualityValue').textContent = Math.round(this.value * 100) + '%';
});
// Показываем/скрываем ползунок качества
document.getElementById('format').addEventListener('change', function() {
const qualityContainer = document.getElementById('qualityContainer');
qualityContainer.style.display = (this.value === 'jpeg' || this.value === 'webp') ? 'block' : 'none';
});
// Отображение выбранных файлов
document.getElementById('imageUpload').addEventListener('change', function() {
const fileNamesDiv = document.getElementById('fileNames');
if (this.files.length === 0) {
fileNamesDiv.innerHTML = 'Нет выбранных файлов';
return;
}
let html = '<ul style="padding-left: 20px;">';
for (let i = 0; i < this.files.length; i++) {
const file = this.files[i];
const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
html += `<li>${file.name} (${sizeMB} MB)</li>`;
}
html += '</ul>';
fileNamesDiv.innerHTML = html;
});
async function processImages() {
const fileInput = document.getElementById('imageUpload');
const files = fileInput.files;
if (files.length === 0) {
alert('Сначала выберите изображения!');
return;
}
// Показываем прогресс
const progressContainer = document.getElementById('progressContainer');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
progressContainer.style.display = 'block';
// Настройки
const scalePercent = document.getElementById('scalePercent').value;
const format = document.getElementById('format').value;
const quality = parseFloat(document.getElementById('quality').value);
// Обрабатываем каждое изображение
for (let i = 0; i < files.length; i++) {
try {
await processSingleImage(files[i], scalePercent, format, quality);
// Обновляем прогресс
const progress = ((i + 1) / files.length) * 100;
progressFill.style.width = progress + '%';
progressText.textContent = `Обработано: ${i + 1}/${files.length}`;
} catch (error) {
console.error(`Ошибка при обработке файла ${files[i].name}:`, error);
alert(`Ошибка при обработке ${files[i].name}: ${error.message}`);
}
}
// Завершаем
progressText.textContent = 'Готово! Все изображения обработаны.';
setTimeout(() => {
progressContainer.style.display = 'none';
progressFill.style.width = '0%';
}, 2000);
}
function processSingleImage(file, scalePercent, format, quality) {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = function() {
const canvas = document.getElementById('previewCanvas');
const ctx = canvas.getContext('2d');
// Рассчитываем новые размеры
let newWidth, newHeight;
if (scalePercent === 'custom') {
const targetWidth = parseInt(document.getElementById('customWidth').value);
const targetHeight = parseInt(document.getElementById('customHeight').value);
if (targetWidth > 0 && targetHeight > 0) {
// Оба размера заданы
newWidth = targetWidth;
newHeight = targetHeight;
} else if (targetWidth > 0) {
// Задана только ширина
newWidth = targetWidth;
newHeight = (img.height * targetWidth) / img.width;
} else if (targetHeight > 0) {
// Задана только высота
newHeight = targetHeight;
newWidth = (img.width * targetHeight) / img.height;
} else {
// Размеры не заданы
newWidth = img.width;
newHeight = img.height;
}
} else {
// Процентное уменьшение
const scale = parseInt(scalePercent) / 100;
newWidth = img.width * scale;
newHeight = img.height * scale;
}
// Устанавливаем размеры canvas
canvas.width = newWidth;
canvas.height = newHeight;
// Отрисовываем изображение с новыми размерами
ctx.drawImage(img, 0, 0, newWidth, newHeight);
// Формируем данные для скачивания
let mimeType, dataUrl;
switch (format) {
case 'png':
mimeType = 'image/png';
dataUrl = canvas.toDataURL(mimeType);
break;
case 'webp':
mimeType = 'image/webp';
dataUrl = canvas.toDataURL(mimeType, quality);
break;
case 'jpeg':
default:
mimeType = 'image/jpeg';
dataUrl = canvas.toDataURL(mimeType, quality);
break;
}
// Создаем имя файла
const originalName = file.name;
const nameWithoutExt = originalName.substring(0, originalName.lastIndexOf('.'));
const extension = format === 'jpeg' ? 'jpg' : format;
const newFileName = `${nameWithoutExt}_resized.${extension}`;
// Скачиваем файл
const link = document.createElement('a');
link.download = newFileName;
link.href = dataUrl;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Очищаем память
URL.revokeObjectURL(img.src);
resolve();
};
img.onerror = function() {
reject(new Error('Не удалось загрузить изображение'));
};
});
}
</script>
Категории:
Категории
Все категории
1С
2040
AD
CG
IOT умный дом
Joomla
Linux
macOS
mysql
php
SEO
Windows
Безопасность
Железо
Защита данных
Простотак
Сети LAN
Создание сайтов
Электрика
Электроника
← Назад к списку
Комментарии
Пока нет комментариев. Будьте первым!