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

Automatically add width and height attributes to image tag

我正在尝试编写一个脚本,自动将图像 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)

代码背后的主要思想如下:

  • 遍历所有博客 posts.
  • 找到每个 post 中的所有 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 变量以指向您的 post 所在的位置。

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

我写了一个插件 (jekyll-image-size) 基本上可以做到这一点,但它是作为模板中的标签来实现的。例如,您可以这样做:

{% imagesize /assets/steam-fish-1.jpeg:img %}

并生成:

<a href="/assets/steam-fish-1.jpeg" width='300' height='150'>

(以图片文件的实际宽高为准)

除了 IMG 标签之外,它还支持视网膜图像缩放和许多备用输出格式:opengraph 标签、css-style props、html-props 以及原始宽度和高度图片的。