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/

相关文章:

html - 特色 slider 的 CSS 溢出问题

ruby - jekyll 的帖子在 github 页面上没有正确显示/格式化(不过网站的其余部分还可以)

html - Github 页面未在子文件夹上加载 css

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

html - Firefox 中不显示 "ff"中的字母 "staff"

html - 无法在 css 中将我的图像居中并且无法删除水平滚动条

html - Twitter Bootstrap MVC 替代方案

iphone - Mobile Safari 和 HTML5 iOS 网络应用程序支持哪些音频文件类型(例如 mp3、ogg)?

markdown - 在 Jekyll(即 Markdown)中,一组 URL 的基本部分可以在链接之间共享吗?

ruby - Jekyll 不在本地提供站点服务