使用js寫一個圖片壓縮的小工具

王铁柱6發表於2024-12-09
function compressImage(file, quality, maxWidth, maxHeight) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = (event) => {
      const img = new Image();
      img.src = event.target.result;

      img.onload = () => {
        let width = img.width;
        let height = img.height;

        // Calculate new dimensions based on maxWidth and maxHeight while maintaining aspect ratio
        if (width > maxWidth) {
          height *= maxWidth / width;
          width = maxWidth;
        }
        if (height > maxHeight) {
          width *= maxHeight / height;
          height = maxHeight;
        }

        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);

        canvas.toBlob((blob) => {
          resolve(blob);
        }, 'image/jpeg', quality); // You can change the MIME type if needed
      };

      img.onerror = (error) => {
        reject(error);
      };
    };

    reader.onerror = (error) => {
      reject(error);
    };
  });
}


// Example usage:

const fileInput = document.getElementById('fileInput'); // Replace with your file input element ID
const compressedImage = document.getElementById('compressedImage'); // Replace with your image element ID


fileInput.addEventListener('change', async (event) => {
  const file = event.target.files[0];

  try {
    const compressedBlob = await compressImage(file, 0.7, 800, 600); // Adjust quality, maxWidth, and maxHeight as needed

    const compressedImageUrl = URL.createObjectURL(compressedBlob);
    compressedImage.src = compressedImageUrl;

    // You can also download the compressed image:
    const downloadLink = document.createElement('a');
    downloadLink.href = compressedImageUrl;
    downloadLink.download = 'compressed_image.jpg'; // Set the desired filename
    downloadLink.textContent = 'Download Compressed Image';
    document.body.appendChild(downloadLink); // Or append to a specific container

  } catch (error) {
    console.error('Image compression error:', error);
  }
});


// HTML Example:
/*
<input type="file" id="fileInput">
<img id="compressedImage" alt="Compressed Image">
*/

Explanation and Key Improvements:

  • Promise-based: Uses Promises for cleaner asynchronous handling.
  • Resizing: Resizes the image proportionally before compressing, using maxWidth and maxHeight parameters. This significantly reduces file size, especially for large images.
  • Error Handling: Includes error handling for FileReader, Image loading, and canvas.toBlob.
  • Download Link: Adds code to create a download link for the compressed image.
  • Clearer Example Usage: Provides a more complete example with HTML snippets and comments.
  • Flexibility: Allows customization of the output image quality, width, and height.
  • JPEG Output: Outputs JPEG by default, which is generally good for photos. You can change the 'image/jpeg' MIME type in canvas.toBlob to 'image/png' if you need PNG output (e.g., for images with sharp lines or transparency).

How to Use:

  1. HTML: Include the HTML snippet provided in the example in your HTML file. Make sure to replace the IDs with your actual element IDs.
  2. JavaScript: Include the JavaScript code in your <script> tag or in a separate .js file and link it to your HTML.
  3. Choose File: Select an image file using the file input.
  4. Compress and Display: The script will compress the image and display it in the compressedImage element. A download link will also be created.

This improved version provides a more robust and user-friendly image compression tool for your frontend development needs. Remember to adjust the quality, maxWidth, and maxHeight parameters to achieve the desired balance between file size and image quality.

相關文章