algui91 algui91 - 6 months ago 26
HTML Question

Automatically add width and height attributes to image tag

I am trying to write a script that automatically add image

to all my
. I've already seen this question:

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

But I am using

My first thought was execute
on my posts directory and for each occurence of an img, get the image
and compute its size. Is this possible?

I have also take a look to
, but it does not work well with Jekyll and local files (Here is a Jekyll filter)

Could you give me some hits on how to accomplish this?

Best regards


I finally came up with a solution, a python script, here it is (I've also created a github gist:


from BeautifulSoup import BeautifulSoup
from os.path import basename, splitext
from PIL import Image
import glob
import io

# Ruta a la carpeta que contiene los ficheros, en este caso
# cualquier fichero markdown
path = "/ruta/ficheros/*.md"

# Iteramos para cada fichero
for fname in glob.glob(path):
    # Lo abrimos
    with,'r',encoding='utf8') as f:
        post =
    # Creamos un objeto BeautifulSoup para parsear el fichero
    soup = BeautifulSoup(post)

    # Para cada etiqueta de imagen que encontremos en el fichero
    for img in soup.findAll('img'):
        if img != None:
                if img['src'].startswith("/assets") == True:
                    # Abrimos la imagen
                    pil ="/ruta/carpeta/imagenes" + img['src'])
                    # Obtenemos su tamaño
                    width, height = pil.size
                    # Modificamos la etiqueta HTML para añadirle el tamaño
                    img['width'] = str(width) + "px"
                    img['height'] = str(height) + "px"
            except KeyError:

    # Guardamos el fichero modificado
    with open(fname, "wb") as file:

Hope it helps