You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免复制Lektor网站中的原始附件图片,仅保留缩略图?

解决Lektor中仅保留附件图片缩略图、不复制原图的问题

当然可以实现!Lektor默认会复制所有关联的附件到输出目录,但我们可以通过自定义构建钩子或者调整附件处理逻辑来只保留缩略图,下面是两种实用的方案:

方案一:使用构建钩子自动删除原图

这个方法的核心是:先让Lektor正常生成缩略图和复制原图,然后在构建完成后自动删除输出目录里的原图。

  1. 创建自定义插件
    在你的Lektor项目根目录下,新建packages/remove-original-images文件夹,然后在里面创建setup.py和remove_original_images.py两个文件:

    setup.py内容:

    from setuptools import setup
    
    setup(
        name='lektor-remove-original-images',
        version='0.1',
        py_modules=['remove_original_images'],
        entry_points={
            'lektor.plugins': [
                'remove-original-images = remove_original_images:RemoveOriginalImagesPlugin',
            ]
        }
    )
    

    remove_original_images.py内容:

    from lektor.pluginsystem import Plugin
    import os
    from lektor.db import Attachment
    
    class RemoveOriginalImagesPlugin(Plugin):
        name = 'Remove Original Images'
        description = 'Automatically deletes original attachment images after build.'
    
        def on_after_build(self, builder, **extra):
            output_dir = builder.destination_path
            # 遍历所有内容项的附件
            for item in builder.pad.query('/'):
                if hasattr(item, 'attachments'):
                    for attachment in item.attachments:
                        if isinstance(attachment, Attachment) and attachment.is_image:
                            # 拼接原图在输出目录的路径
                            original_file_path = os.path.join(output_dir, attachment.url_path.lstrip('/'))
                            if os.path.exists(original_file_path):
                                os.remove(original_file_path)
    
  2. 启用插件
    在项目的lektorproject文件中,添加这个插件:

    [packages]
    lektor-remove-original-images = 0.1
    
  3. 正常生成缩略图
    在你的模板中,继续使用thumbnail过滤器生成缩略图,比如:

    {% for att in this.attachments if att.is_image %}
        <img src="{{ att.thumbnail(300, 200, crop=True) }}" alt="{{ att.filename }}">
    {% endfor %}
    

    当你运行lektor build或lektor server时,插件会在构建完成后自动删除输出目录中的原图,只保留生成的缩略图。

方案二:调整附件存储方式,避免原图被复制

如果你不想用插件,也可以换一种方式管理图片:

  • 将原图放在项目的assets目录下,而不是作为内容的附件关联。

  • 在configs/assets.ini中添加排除规则,阻止原图被复制到输出目录:

    [exclude]
    images/originals/*.jpg
    images/originals/*.png
    
  • 在模板中,通过asset对象生成缩略图:

    {% set original_img = get_asset('images/originals/my-photo.jpg') %}
    <img src="{{ original_img.thumbnail(300, 200, crop=True) }}" alt="My Photo">
    

    这种方式下,原图会留在assets目录中不被复制,只有生成的缩略图会出现在输出目录里。

注意事项

  • 如果你使用lektor server进行开发,方案一的插件会在每次构建后删除原图,不会影响开发预览(因为预览时缩略图已经生成)。
  • 确保你只在模板中引用缩略图,不要直接引用原图的URL,否则用户访问时会出现404错误。

内容的提问来源于stack exchange,提问作者tgpfeiffer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:07:39