一、學習目標
這一天的目標是學習如何使用JavaScript在不失真太多的情況下壓縮圖片大小,以便讓上傳速度更快、相簿載入更順暢。
二、學習過程與方法
我使用 canvas
元素來重繪圖片,設定最大寬高為 800 像素。再透過 canvas.toDataURL("image/jpeg", 0.8)
將圖片輸出為壓縮後的Base64格式。
三、實作成果
上傳後圖片會自動壓縮並顯示在相簿中。旁邊的資訊文字會顯示壓縮前後的變化,明確指出尺寸縮減與容量節省,整體操作流暢且效果顯著。
四、主要程式碼區塊
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>Day7 - 圖片壓縮與預覽</title>
<style>
/* 主題配色:與前幾天統一 */
: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>Day7:自動壓縮圖片並顯示壓縮後的預覽與資訊</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);
// 轉成壓縮後的 Data URL
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("Day7:圖片壓縮與預覽完成");
</script>
</body>
</html>