Automatically add width and height attributes to image tag
Asked Answered
A

4

5

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)

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

Aurita answered 27/6, 2016 at 11:38 Comment(3)
You could just use JavaScript to do this on the client side. Is there a reason that wouldn't work for you? I'd also be curious to hear why you need to do this at all.Draggletailed
@KevinWorkman because I am implementing Google AMP pages and the amp-img needs those attributes to be specified.Aurita
@KevinWorkman Image tags should always have height and width attributes, but they're not required in order to display. Every SEO tool will flag them up if missing.Farrica
A
4

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

Here is the main idea behind the code:

  • Iterate over all blog posts.
  • Find all img tags in each post.
  • Extract the content of the src attribute.
  • Open the image and extract its size.
  • Write image size in the img attribues width and height.

The code:

#!/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))

How to use

Just create the script in you machine and change path variable to point where your posts are.

Hope it helps, I've also wrote a blog post about this issue

Aurita answered 1/7, 2016 at 10:48 Comment(4)
Where did you add it? Could you explain how to use it?Hoplite
@Hoplite Hi, I updated the answer, commenting on the code and giving general steps. Hope it helps.Aurita
Thanks but still not clear to me. What language is it? How do you execute it? What is BeautifulSoup ?Hoplite
It is python, you need yo save te code in a file, give it execution permissions, run it.Aurita
S
3

I wrote a plugin (jekyll-image-size) that does basically this, but it does it as a tag in your templates. For example, you can do this:

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

And it generates:

<a href="/assets/steam-fish-1.jpeg" width='300' height='150'>

(with the actual width and height of the image file)

It also supports retina-image-scaling and many alternate output-formats beyond just IMG tags: opengraph tags, css-style props, html-props, and the raw width and height of the image.

Supplicate answered 1/8, 2019 at 21:47 Comment(0)
S
1

I wrote this C tool for my own needs :

https://github.com/jfdelnero/TrucsEnVrac/tree/master/Tools/patch_html

This tool checks / fixes / add any missing/bad img "width" and "height" attributes. It also add any missing "alt" img attribute.

Run on Linux and need the "convert" tool.

Soneson answered 24/12, 2022 at 11:38 Comment(0)
S
0

Shameless plug: I wrote a search-and-replace tool that can add width and height attributes automatically. You need to use a built-in function that is similar to PHP's getimagesize and returns the correct width="..." height="..." string.

Sanburn answered 14/7 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.