Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html>
<head>
	<title>Image Compression Tool</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<div class="card">
		<h1>Image Compression Tool</h1>
		<form id="upload-form" action="#" method="post" enctype="multipart/form-data">
			<label class="upload-label" for="files">Select up to 20 images to compress:</label>
			<input type="file" id="files" name="files[]" multiple accept=".jpg,.png,.webp">
			<button class="upload-button" type="submit">Compress</button>
		</form>
	</div>
	<div class="card">
		<h2>Download Compressed Images</h2>
		<div id="downloads"></div>
	</div>
	<script src="script.js"></script>
</body>
</html>

              
            
!

CSS

              
                body {
	font-family: Arial, sans-serif;
	margin: 0;
	padding: 0;
	background-color: #f6f6f6;
}

.card {
	max-width: 600px;
	margin: 50px auto;
	background-color: #fff;
	border-radius: 5px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

h1, h2 {
	text-align: center;
	margin-top: 20px;
}

form {
	padding: 20px;
}

.upload-label {
	display: block;
	margin-bottom: 10px;
	font-size: 18px;
	font-weight: bold;
	color: #444;
}

input[type="file"] {
	display: block;
	margin-bottom: 20px;
}

.upload-button {
	background-color: #4CAF50;
	color: white;
	padding: 10px 20px;
	border: none;
	border-radius: 5px;
	cursor: pointer;
}

.upload-button:hover {
	background-color: #3e8e41;
}

#downloads {
	max-width: 600px;
	margin: 20px auto;
	padding: 20px;
	background-color: #fff;
	border-radius: 5px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

a {
	display: block;
	margin-bottom: 10px;
	font-size: 18px;
	color: #444;
}

a:hover {
	color: #4CAF50;
}

              
            
!

JS

              
                const form = document.querySelector('#upload-form');
const downloadsDiv = document.querySelector('#downloads');

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const files = form.elements.files.files;
  if (files.length === 0) {
    alert('Please select at least one file.');
    return;
  }
  if (files.length > 20) {
    alert('Please select no more than 20 files.');
    return;
  }
  clearDownloads();
  const compressedFiles = await Promise.all([...files].map(compressFile));
  compressedFiles.forEach(downloadFile);
});

function compressFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      const img = new Image();
      img.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = canvas.width * (img.height / img.width); // Set the height based on the aspect ratio
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        canvas.toBlob((blob) => {
          let compressedFile;
          if (file.type === 'image/png') {
            const quantize = new RgbQuant({
              colors: 256,
              palette: Array.from({ length: 256 }).map((_, i) => i * 0x101),
            });
            quantize.sample(canvas);
            const indexedCanvas = quantize.reduce(canvas);
            indexedCanvas.toBlob((blob) => {
              compressedFile = new File([blob], `(${getTimestamp()}) ${file.name}`, { type: file.type });
              resolve(compressedFile);
            }, file.type, 0.5); // Use a compression quality of 0.5 for indexed PNG files
          } else {
            compressedFile = new File([blob], `(${getTimestamp()}) ${file.name}`, { type: file.type });
            resolve(compressedFile);
          }
        }, file.type, 0.3); // Use a compression quality of 0.3 for JPEG and WebP files
      };
      img.onerror = () => {
        reject(new Error(`Failed to load image ${file.name}`));
      };
      img.src = event.target.result;
    };
    reader.readAsDataURL(file);
  });
}

function getTimestamp() {
  const date = new Date();
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}`;
}

function pad(num) {
  return num.toString().padStart(2, '0');
}

function downloadFile(file) {
  const url = URL.createObjectURL(file);
  const link = document.createElement('a');
  link.href = url;
  link.download = file.name.replace(/\.(jpg|png|webp)$/, `(compressed).$1`);
  link.textContent = `Download ${link.download}`;
  downloadsDiv.appendChild(link);
}

function clearDownloads() {
  downloadsDiv.innerHTML = '';
}

              
            
!
999px

Console