Uppy 缩略图生成器
@uppy/thumbnail-generator
为添加到 Uppy 中的图片生成等比缩略图(文件预览)。
何时使用此功能?
此插件默认包含在 Dashboard 插件中,对于自定义 UI 中显示图像预览也非常有用。
缩略图仅针对本地文件生成。通过 Companion 的远程文件通常不会有缩略图,因为它们是在服务器上下载的。某些提供商,如 Google Drive,已经在其 API 响应中内置了缩略图。
安装
npm
npm install @uppy/thumbnail-generator
yarn
yarn add @uppy/thumbnail-generator
CDN
谨慎
该捆绑包包含了大部分的 Uppy 插件,因此这种方法不建议在生产环境中使用,因为当您可能只使用少数几个插件时,您的用户却需要下载所有插件。
但在加速开发环境方面,这可能会很有帮助,所以不妨在开始时使用它来提速。<!-- 1. Add CSS to `<head>` --> <link href="https://releases.transloadit.com/uppy/v3.27.3/uppy.min.css" rel="stylesheet"> <!-- 2. Initialize --> <div id="uppy"></div> <script type="module"> import { Uppy, ThumbnailGenerator } from "https://releases.transloadit.com/uppy/v3.27.3/uppy.min.mjs" const uppy = new Uppy() uppy.use(ThumbnailGenerator) </script>
使用
如果您使用的是 Dashboard,那么它已经安装好了。如果您想为自己的 UI 程序化地使用它:
import Uppy from "@uppy/core";
import ThumbnailGenerator from "@uppy/thumbnail-generator";
const uppy = new Uppy();
uppy.use(ThumbnailGenerator);
uppy.on("thumbnail:generated", (file, preview) => doSomething(file, preview));
API
选项
id
此插件的唯一标识符( string
,默认:'ThumbnailGenerator'
)。
locale
export default {
strings: {
generatingThumbnails: "正在生成缩略图...",
},
};
thumbnailWidth
生成缩略图的宽度( number
,默认:200
)。
缩略图始终是等比例且不被裁剪的。如果提供了宽度,高度会自动计算以匹配比例。如果同时给出了宽度和高度,只有宽度会被考虑。
thumbnailHeight
生成缩略图的高度( number
,默认:200
)。
缩略图始终是等比例且不被裁剪的。如果提供了高度,宽度会自动计算以匹配比例。如果同时给出了宽度和高度,只有宽度会被考虑。
生成一个高度为 300px 并自动计算宽度以匹配比例的缩略图:
uppy.use(ThumbnailGenerator, { thumbnailHeight: 300 });
生成一个宽度为 300px 并自动计算高度以匹配比例的缩略图(忽略给定的高度):
uppy.use(ThumbnailGenerator, { thumbnailWidth: 300, thumbnailHeight: 300 });
thumbnailType
生成缩略图的 MIME 类型( string
,默认:'image/jpeg'
)。
这在您希望缩略图支持透明度并切换到 image/png
时非常有用。
waitForThumbnailsBeforeUpload
是否等待所有缩略图准备就绪后再开始上传( boolean
,默认:false
)。
如果设置为 true
,缩略图生成器将触发 Uppy 的内部处理阶段,并等待 thumbnail:all-generated
事件,然后继续进行上传阶段。这很有用,因为缩略图生成器还会向图像添加 EXIF 数据,如果我们等待它完成处理,这些数据在上传后会在服务器上可用。
事件
您可以使用
on
和once
来监听这些事件。
thumbnail:generated
当缩略图生成时,会携带 file
和 preview
本地 URL 作为参数发出:
uppy.on("thumbnail:generated", (file, preview) => {
const img = document.createElement("img");
img.src = preview;
img.width = 100;
document.body.appendChild(img);
});