Automatic Image Width and Height Attribute
Updated: Sunday, 07 August 2016
Applies only for local images.
Add this snippet to your functions.php
file:
Filter::add('content', function($content) use($config) {
if(strpos($content, '<img ') === false) return $content;
return preg_replace_callback('#<img\s+.*?(\s*\/?>)#s', function($matches) use($config) {
extract(Converter::attr($matches[0], array(), array(), false));
if(isset($attributes['width']) && isset($attributes['height'])) {
return $matches[0]; // image width and height already defined
}
if(isset($attributes['src'])) {
$src = Converter::url($attributes['src']); // convert relative URL to full URL
$src = File::path($src); // convert public URL to private file path
if($path = File::exist($src)) {
$s = Image::take($path)->inspect(); // inspect local image data
$attributes['width'] = $s['width']; // set image width
$attributes['height'] = $s['height']; // set image height
$out = '<img'; // re-build image HTML
foreach($attributes as $k => $v) {
$out .= ' ' . $k . '="' . $v . '"'; // put attribute(s) data
}
return $out . $matches[1]; // output the result!
}
return $matches[0]; // external image `src` or invalid image `src` value
}
return $matches[0]; // --ibid
}, $content);
});
Save changes.