phpcodeigniterparsedown

Parsedown set image width and height


Currently I use CodeIgniter 3.1.3 and Parsedown / Markdown Guide

With parse down I would like to be able to set the width and height of the image

![enter image description][1]

[1]: http://www.example.com/image.png '100x200' <-- widthxheight

I try the the way above but sets image title instead.

Output would be

<img src="http://www.example.com/image.png" width="100" height="200" alt="enter image description">

Question in parsedown library is there any way to modify it so can get and set the width and height of image?

protected function inlineImage($Excerpt)
{
    if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
    {
        return;
    }

    $Excerpt['text']= substr($Excerpt['text'], 1);

    $Link = $this->inlineLink($Excerpt);

    if ($Link === null)
    {
        return;
    }

    $Inline = array(
        'extent' => $Link['extent'] + 1,
        'element' => array(
            'name' => 'img',
            'attributes' => array(
                'src' => $Link['element']['attributes']['href'],
                'alt' => $Link['element']['text'],
                'width' => '',
                'height' => ''
            ),
        ),
    );

    $Inline['element']['attributes'] += $Link['element']['attributes'];

    unset($Inline['element']['attributes']['href']);

    return $Inline;
}

Solution

  • Last element from this (reference) syntax [1]: http://www.example.com/image.png '100x200'

    Will be passed as title attribute, so you might do it this way:

    class MyParsedown extends Parsedown
    {
        protected function inlineImage($Excerpt)
        {
            $Inline = parent::inlineImage($Excerpt);
    
            if (!isset($Inline['element']['attributes']['title'])) { return $Inline; }
    
            $size = $Inline['element']['attributes']['title'];
    
            if (preg_match('/^\d+x\d+$/', $size)) {
                list($width, $height) = explode('x', $size);
    
                $Inline['element']['attributes']['width'] = $width;
                $Inline['element']['attributes']['height'] = $height;
    
                unset ($Inline['element']['attributes']['title']);
            }
    
            return $Inline;
        }
    }
    

    Attribute will be changed to width+height if title matches NUMERICxNUMERIC pattern. You might limit number of digits or size to protect breaking the page, also leading 0 should be excluded (or sizes with only 0).