iT邦幫忙

2

30天做出一個線上相簿

  • 分享至 

  • xImage
  •  

Day 8 學習報告

主題:多圖片上傳與相簿顯示

一、學習目標

今天的主要目的是讓系統能同時壓縮多張圖片,這樣使用者上傳多張照片時,不僅能節省空間,也能保持載入速度。這樣的功能在線上相簿中非常實用,能減少伺服器壓力並提升使用體驗。


二、學習過程與方法

我先使用 HTML 的 <input type="file" multiple> 讓使用者可以一次選擇多張圖片,接著透過JavaScript的 FileReader() 讀取每張圖片資料。每張圖片都會被送入一個 canvas 進行壓縮,程式自動判斷長寬比例,不會讓圖片變形。最後將壓縮後的結果以DataURL顯示在畫面上,同時在資訊欄中顯示壓縮後的寬高與原始大小比較。


三、實作成果

上傳多張圖片後,每張圖片都會自動壓縮,並顯示在相簿中。資訊欄能清楚看到「原始大小」與「壓縮後尺寸」,效果明顯。整體操作流暢,畫面仍保持乾淨整齊。


四、主要程式碼區塊

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>Day8 - 批次壓縮多張圖片</title>

  <style>
    /* 主題統一設計(延續 Day1~Day7) */
    :root {
      --bg: #ffffff;
      --primary: darkorange;
      --accent: coral;
      --text: #333;
      --muted: #777;
      --border: #e6e6e6;
      --btn: #ff8c42;
      --btn-hover: #ff6a00;
      --card-bg: #fff;
    }

    /* 基本結構 */
    body {
      background-color: var(--bg);
      font-family: "Microsoft JhengHei", Arial, sans-serif;
      margin: 20px;
      text-align: center;
      color: var(--text);
    }

    h1 {
      color: var(--primary);
    }

    p {
      color: var(--accent);
      font-size: 18px;
    }

    /* 上傳按鈕樣式 */
    input[type="file"] {
      margin: 15px 0;
      padding: 8px;
      border-radius: 6px;
      border: 1px solid var(--border);
      font-size: 16px;
      cursor: pointer;
    }

    /* 相簿區排列 */
    #gallery {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      gap: 20px;
      margin-top: 20px;
    }

    /* 圖片卡片樣式 */
    .photo-card {
      background: var(--card-bg);
      border: 1px solid var(--border);
      border-radius: 10px;
      padding: 10px;
      box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
      text-align: center;
    }

    .photo-card img {
      width: 100%;
      border-radius: 10px;
      border: 2px solid #ddd;
    }

    /* 資訊文字樣式 */
    .info {
      font-size: 14px;
      color: var(--muted);
      margin-top: 8px;
      line-height: 1.5;
      word-wrap: break-word;
      overflow-wrap: anywhere; /* 防止文字超出外框 */
    }
  </style>
</head>

<body>
  <h1>我的線上相簿</h1>
  <p>Day8:支援批次壓縮多張圖片,並顯示壓縮效果資訊</p>

  <!-- 上傳區 -->
  <input type="file" id="upload" accept="image/*" multiple>

  <!-- 相簿展示區 -->
  <div id="gallery"></div>

  <script>
    const upload = document.getElementById("upload");
    const gallery = document.getElementById("gallery");

    // 上傳多張圖片
    upload.addEventListener("change", function () {
      gallery.innerHTML = ""; // 清空舊的內容

      Array.from(this.files).forEach(file => {
        const reader = new FileReader();

        reader.onload = function (e) {
          const img = new Image();

          img.onload = function () {
            // 設定最大寬高
            const maxWidth = 800;
            const maxHeight = 800;
            let width = img.width;
            let height = img.height;

            // 若圖片過大則等比例縮小
            if (width > maxWidth || height > maxHeight) {
              if (width > height) {
                height = Math.round((maxWidth / width) * height);
                width = maxWidth;
              } else {
                width = Math.round((maxHeight / height) * width);
                height = maxHeight;
              }
            }

            // 用 Canvas 進行壓縮
            const canvas = document.createElement("canvas");
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);

            // 轉成壓縮後 DataURL
            const compressedDataUrl = canvas.toDataURL("image/jpeg", 0.8);

            // 建立圖片卡片
            const card = document.createElement("div");
            card.classList.add("photo-card");

            const newImg = document.createElement("img");
            newImg.src = compressedDataUrl;

            const shortName =
              file.name.length > 25 ? file.name.slice(0, 25) + "..." : file.name;

            const info = document.createElement("p");
            info.classList.add("info");
            info.textContent =
              `檔名: ${shortName} | 原始大小: ${(file.size / 1024).toFixed(1)} KB | 壓縮後尺寸: ${width}x${height}`;

            card.appendChild(newImg);
            card.appendChild(info);
            gallery.appendChild(card);
          };

          img.src = e.target.result;
        };

        reader.readAsDataURL(file);
      });
    });

    console.log("Day8:批次壓縮多張圖片完成");
  </script>
</body>
</html>

https://ithelp.ithome.com.tw/upload/images/20251015/201787609bst35MMUQ.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言