Snippet · Mecha CMS

Code snippet collection for developers.

Automatic Image Width & Height Attribute

Author: Taufik Nurrohman · 287 Views

Tweet

Applies only for local images.

Hook::set('page.content', function($content) {
    if (stripos($content, '<img ') === false) {
        return $content;
    }
    return preg_replace_callback('#<img .*?>#', function($m) {
        $img = HTML::apart($m[0], false);
        if (isset($img[2]['width']) && isset($img[2]['height'])) {
            return $m[0]; // Image `width` and `height` attribute already set
        }
        if (isset($img[2]['src'])) {
            $src = URL::long($img[2]['src']); // Convert relative URL to full URL
            $src = To::path($src); // Convert public URL to private file path
            if ($path = File::exist($src)) {
                $s = getimagesize($path); // Inspect local image data
                $img[2]['width'] = $s[0]; // Set image `width` attribute
                $img[2]['height'] = $s[1]; // Set image `height` attribute
                return call_user_func_array('HTML::unite', $img); // Re-unite the image!
            }
            return $m[0]; // External image `src` or invalid image `src` value
        }
        return $m[0]; // Image with no `src` attribute
    }, $content);
}, 2.1);

0 Comments

No comments yet.