html - 自动为图片标签添加宽高属性

标签 html jekyll

我正在尝试编写一个脚本,自动将图像 widthheight 添加到我所有的 img。我已经看到这个问题了:

Automatically adding width and height attributes to <img> tags with a PHP function

但我正在使用 jekyll

我的第一个想法是在我的帖子目录上执行 grep,对于每次出现的 img,获取图像 URI 并计算其大小。这可能吗?

我也查看了 fastImage,但它不适用于 Jekyll 和本地文件 (Here is a Jekyll filter)

你能给我一些关于如何实现这一点的建议吗?

最佳答案

我终于想出了一个解决方案,一个 python 脚本,就在这里(我还创建了一个 github gist)

下面是代码背后的主要思想:

  • 遍历所有博客文章。
  • 找到每个帖子中的所有 img 标签。
  • 提取src属性的内容。
  • 打开图像并提取其尺寸。
  • img 属性 widthheight 中写入图像大小。

代码:

#!/bin/python
from BeautifulSoup import BeautifulSoup
from os.path import basename, splitext
from PIL import Image
import glob

# Path where the posts are, in markdown format
path = "/ruta/ficheros/*.md"

# Iterate over all posts
for fname in glob.glob(path):
    # Open the post
    f = open(fname)
    # Create a BeautifulSoup object to parse the file
    soup = BeautifulSoup(f)
    f.close()
    # For each img tag:
    for img in soup.findAll('img'):
        if img != None:
            try:
                if img['src'].startswith("/assets") == True:
                    # Open the image
                    pil = Image.open("/ruta/carpeta/imagenes" + img['src'])
                    # Get its size
                    width, height = pil.size
                    # Modify img tag with image size
                    img['width'] = str(width) + "px"
                    img['height'] = str(height) + "px"
            except KeyError:
                pass
    # Save the updated post
    with open(fname, "wb") as file:
        file.write(str(soup))

使用方法

只需在您的机器上创建脚本并更改 path 变量以指向您的帖子所在的位置。

希望有帮助,我也有wrote a blog post about this issue

关于html - 自动为图片标签添加宽高属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38052994/

相关文章:

javascript - 有没有办法在 Three.js 中有透明的视频背景?

javascript - 禁用光标点击而不阻止突出显示

javascript - 隐藏滚动条而不影响页面宽度或不稳定的页面重新呈现

ruby - 敬畏导航: sort pages by category

Jekyll - 你可以使用 Liquid 来引用 Front Matter 变量吗

html - CSS相对定位和流程

html - common.css 中的 MediaWiki CSS 适用于 Vector 但不适用于 MinervaNeue

ruby - 'pathutil' ruby​​ gem 是否与 jekyll (v3.9.0) 和 ruby​​ (v3.0.0) 兼容?

github - 删除 GitHub Pages document.title 中的 "by [username]"

javascript - 如何在 Javascript 文件中包含使用 Jekyll 定义的液体/全局变量?