|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 6 | + <title>Image Compressor</title> |
| 7 | + <script src="https://cdn.jsdelivr.net/npm/compressorjs@1.2.1/dist/compressor.min.js"></script> |
| 8 | + <style> |
| 9 | + body { |
| 10 | + font-family: Arial, sans-serif; |
| 11 | + text-align: center; |
| 12 | + margin: 50px; |
| 13 | + } |
| 14 | + .container { |
| 15 | + max-width: 400px; |
| 16 | + margin: auto; |
| 17 | + padding: 20px; |
| 18 | + border: 1px solid #ddd; |
| 19 | + border-radius: 10px; |
| 20 | + box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); |
| 21 | + } |
| 22 | + input, button { |
| 23 | + margin-top: 10px; |
| 24 | + } |
| 25 | + .file-info { |
| 26 | + margin-top: 10px; |
| 27 | + } |
| 28 | + .download { |
| 29 | + display: none; |
| 30 | + margin-top: 10px; |
| 31 | + } |
| 32 | + </style> |
| 33 | +</head> |
| 34 | +<body> |
| 35 | + <div class="container"> |
| 36 | + <h2>Image Compressor</h2> |
| 37 | + <input type="file" id="imageInput" accept="image/*"> |
| 38 | + <div class="file-info" id="fileInfo"></div> |
| 39 | + <button id="downloadBtn" class="download">Download Compressed Image</button> |
| 40 | + </div> |
| 41 | + |
| 42 | + <script> |
| 43 | + function humanFileSize(size) { |
| 44 | + let i = Math.floor(Math.log(size) / Math.log(1024)); |
| 45 | + return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB'][i]; |
| 46 | + } |
| 47 | + |
| 48 | + document.getElementById('imageInput').addEventListener('change', function (event) { |
| 49 | + const file = event.target.files[0]; |
| 50 | + if (!file) return; |
| 51 | + |
| 52 | + document.getElementById('fileInfo').innerHTML = `Original Size: ${humanFileSize(file.size)}`; |
| 53 | + |
| 54 | + new Compressor(file, { |
| 55 | + quality: 0.6, |
| 56 | + success(result) { |
| 57 | + const compressedBlob = result; |
| 58 | + document.getElementById('fileInfo').innerHTML += `<br>Compressed Size: ${humanFileSize(compressedBlob.size)}`; |
| 59 | + |
| 60 | + const downloadBtn = document.getElementById('downloadBtn'); |
| 61 | + const url = URL.createObjectURL(compressedBlob); |
| 62 | + downloadBtn.style.display = 'inline-block'; |
| 63 | + downloadBtn.onclick = function() { |
| 64 | + const a = document.createElement('a'); |
| 65 | + a.href = url; |
| 66 | + a.download = 'compressed-image.jpg'; |
| 67 | + document.body.appendChild(a); |
| 68 | + a.click(); |
| 69 | + document.body.removeChild(a); |
| 70 | + }; |
| 71 | + }, |
| 72 | + error(err) { |
| 73 | + console.error(err.message); |
| 74 | + }, |
| 75 | + }); |
| 76 | + }); |
| 77 | + </script> |
| 78 | +</body> |
| 79 | +</html> |
0 commit comments