当前位置:首页 > JavaScript

js实现缩略图

2026-01-30 12:16:11JavaScript

使用 Canvas 实现缩略图

通过 Canvas 的 drawImage 方法缩放图片并生成缩略图。将原始图片绘制到缩小后的 Canvas 上,再转换为 Base64 或 Blob 数据。

function createThumbnail(file, maxWidth, maxHeight) {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement('canvas');
      let width = img.width;
      let height = img.height;

      // 计算缩放比例
      if (width > maxWidth) {
        height = Math.round((height * maxWidth) / width);
        width = maxWidth;
      }
      if (height > maxHeight) {
        width = Math.round((width * maxHeight) / height);
        height = maxHeight;
      }

      // 绘制缩略图
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);

      // 转换为 Blob
      canvas.toBlob(resolve, 'image/jpeg', 0.7);
    };
    img.src = URL.createObjectURL(file);
  });
}

使用第三方库(如 sharp.js)

在 Node.js 环境中,可使用 sharp 库高效处理图片缩略图。需先安装库:npm install sharp

const sharp = require('sharp');

async function generateThumbnail(inputPath, outputPath, width, height) {
  await sharp(inputPath)
    .resize(width, height, { fit: 'inside' })
    .toFile(outputPath);
}

纯前端缩略图预览

通过 URL.createObjectURL 实现上传前的本地预览,适合不要求高质量缩略图的场景。

function previewThumbnail(file, targetElementId) {
  const reader = new FileReader();
  reader.onload = (e) => {
    const img = document.createElement('img');
    img.src = e.target.result;
    img.style.maxWidth = '200px';
    document.getElementById(targetElementId).appendChild(img);
  };
  reader.readAsDataURL(file);
}

响应式缩略图(CSS 方案)

利用 CSS 的 object-fit 属性实现容器内自适应缩略图,不改变原始文件。

<div class="thumbnail-container">
  <img src="original.jpg" class="thumbnail" />
</div>

<style>
  .thumbnail-container {
    width: 200px;
    height: 150px;
    overflow: hidden;
  }
  .thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

服务端生成缩略图(Node.js + Jimp)

使用 Jimp 库处理图片,适合需要后端处理的场景。

js实现缩略图

const Jimp = require('jimp');

async function createThumbnail(inputPath, outputPath) {
  const image = await Jimp.read(inputPath);
  await image
    .resize(200, Jimp.AUTO)
    .quality(80)
    .writeAsync(outputPath);
}

标签: 缩略图js
分享给朋友:

相关文章

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。 &…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…

js实现导航菜单

js实现导航菜单

使用HTML和CSS创建基础结构 导航菜单的基础结构通常由HTML的无序列表(<ul>)和列表项(<li>)组成,每个列表项包含一个链接(<a>)。CSS用于样式化…