Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 自动向图像标记添加宽度和高度属性_Html_Jekyll - Fatal编程技术网

Html 自动向图像标记添加宽度和高度属性

Html 自动向图像标记添加宽度和高度属性,html,jekyll,Html,Jekyll,我正在尝试编写一个脚本,自动将图像width和height添加到我所有的img。我已经看到了这个问题: 但是我使用的是jekyll 我的第一个想法是在我的posts目录上执行grep,对于每次出现的img,获取图像URI,并计算其大小。这可能吗 我还查看了fastImage,但它不能很好地处理Jekyll和本地文件() 你能给我介绍一下如何实现这一点吗?我终于想出了一个解决方案,一个python脚本,在这里(我还创建了一个 以下是代码背后的主要思想: 迭代所有博客文章 在每个帖子中查找所有i

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

但是我使用的是
jekyll

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

我还查看了
fastImage
,但它不能很好地处理Jekyll和本地文件()


你能给我介绍一下如何实现这一点吗?

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

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

  • 迭代所有博客文章
  • 在每个帖子中查找所有
    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
变量更改为帖子所在的位置

希望能有所帮助,我也写了一个插件(),基本上可以做到这一点,但它可以作为模板中的标签来实现。例如,您可以这样做:

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


(图像文件的实际宽度和高度)


它还支持视网膜图像缩放和除IMG标记之外的许多其他输出格式:opengraph标记、css样式的道具、html道具以及图像的原始宽度和高度。

您可以在客户端使用JavaScript来完成这项工作。有什么原因对您不起作用吗?我也想知道您为什么需要在全部。@KevinWorkman,因为我正在实现Google AMP页面,AMP img需要指定这些属性。@KevinWorkman图像标签应该始终具有高度和宽度属性,但它们不是显示所必需的。如果缺少,每个SEO工具都会标记它们。你在哪里添加的?你能解释一下如何使用它吗?@Alvaro Hi,I u更新答案,评论代码并给出一般步骤。希望有帮助。谢谢,但我还是不清楚。它是什么语言?如何执行它?什么是BeautifulSoup?它是python,你需要将代码保存在文件中,给它执行权限,然后运行它。