Image resizing and caption from ALT field

Resizing Ghost blog image with MD and pick up the ALT of the image

This is just a quick resizing code snippet if you are looking for something easy and basic function.
These few lines gives a quick control on the image size in case you don’t want a full width or full screen image.
You create the MD image as below to resize the image by 50% for instance:

![This is the ALT and caption of an image. @50%](https://blog.yourdomain.com/storage/image.png)

This will create the below img tag in HTML. The @50% will be truncated from the caption, but it will be still present in the ALT. You can use whatever size after the @ between 1 and 100. Then the integer has to be followed by %.

<figure class="image">
  <img src="https://blog.yourdomain.com/storage/image.png" 
       alt="This is the ALT and caption of an image.@50%" 
       style="width: 55%; display: block; margin: auto;">
  <figcaption>This is the ALT and caption of an image.</figcaption>
</figure>
<script>
  // Creates Captions from Alt tags
  $(".post-content img").each(
  function() {
    // Let's put a caption if there is one
    var altImg = $(this).attr("alt")
    if (altImg) {
      var widthImg = "100%";
      var matching = altImg.match('@(100|[1-9][0-9]?)\%$')
      if (matching !== null){
        widthImg = matching[1] + "%";
        altImg =  altImg.slice(0,matching.index);
      }
      $(this).css({"width":widthImg, "display": "block", "margin": "auto"});
      $(this).wrap(
      '<figure class="image"></figure>'
      ).after(
      '<figcaption>' +
        altImg +
        '</figcaption>'
        );
      }
    });
  </script> 
1 Like