How to grab first image from post to excerpt

Without editing front matter how to add first image to post excerpt. I used below code
{% assign foundImage = 0 %}
{% assign images = post.content | split:"<img " %}
{% for image in images %}
{% if image contains ‘src’ %}

      {% if foundImage == 0 %}
          {% assign html = image | split:"/>" | first %}
          {% assign tags = html | split:" " %}
          {% for tag in tags %}
            {% if tag contains 'src' %}
              <img {{ tag }} />
            {% endif %}
          {% endfor %}
          {% assign foundImage = 1 %}
      {% endif %}
  {% endif %}
{% endfor %}

It grab images but it also grab other stuff like pdf from posts.
Please help. Thanks.

1 Like