algui91 algui91 - 5 months ago 20
HTML Question

Automatically add width and height attributes to image tag

I am trying to write a script that automatically add image

width
and
height
to all my
img
. I've already seen this question:

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

But I am using
jekyll
.

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

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

https://github.com/juusaw/amp-jekyll/blob/master/amp_filter.rb

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

Best regards

Answer

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

#!/bin/python

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 io.open(fname,'r',encoding='utf8') as f:
        post = f.read()
    # 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:
            try:
                if img['src'].startswith("/assets") == True:
                    # Abrimos la imagen
                    pil = Image.open("/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:
                pass

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

Hope it helps