我正在尝试编写一个脚本,自动将图像 width
和 height
添加到我所有的 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
属性width
和height
中写入图像大小。
代码:
#!/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/