AttachImageSize

Summary: Generate width and height attributes for attached images
Version: 20210213
Maintainer: Petko
Categories: Images, PHP55, PHP72, PHP80
License: GPL2+

Description

Generate width and height attributes for attached images

The default Attach: markup for attached images doesn't include the image width and height attributes in the HTML tag. This recipe makes it possible to override this, and to automatically set these attributes.

Installation

This function is a derivative work from core PmWiki functions, hence licensed under the GNU GPL v2 or later.

Place the following code in local/config.php :

function LinkImageSize($pagename, $imap, $path, $alt, $txt, $fmt=NULL) {
  global $FmtV, $UploadFileFmt;
  if(!preg_match('/\\.(gif|jpe?g|png|webp)$/i', $path)) 
    return LinkUpload($pagename, $imap, $path, $alt, $txt, $fmt);
  if (preg_match('!^(.*)/([^/]+)$!', $path, $match)) {
    $pagename = MakePageName($pagename, $match[1]);
    $path = $match[2];
  }
  $upname = MakeUploadName($pagename, $path);
  $filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
  $s = @getimagesize($filepath);
  $FmtV['$ImageSize'] = @$s[3];
  $r = LinkUpload($pagename, $imap, $path, $alt, $txt, $fmt);
  $FmtV['$ImageSize'] = '';
  return $r;
}
$LinkFunctions['Attach:'] = 'LinkImageSize';
$ImgTagFmt="<img src='\$LinkUrl' alt='\$LinkAlt' title='\$LinkAlt' \$ImageSize />";
$FmtV['$ImageSize'] = '';

See a derivative implementation at AttachImageSize-Talk, with <picture> tags and multiple source images for different screen resolutions.

Notes

See this message by Pm for limits of such a method. Notably:

  • it only works with images attached to the wiki page and displayed via Attach: markup, not with other images (external, or via Path: or http: links);
  • if the getimagesize() PHP function is not enabled, the attributes are not set;
  • if an author tries to override the size via a wikistyle, it may not work well in all browsers.

Release Notes

  • 20210213 - if an attached file is not a picture, it now directly calls LinkUpload().
  • 20090106 - first public release

See Also

Contributors

The recipe is written and maintained by Petko. Parts of code from scripts/upload.php by Pm.

Comments

See discussion at AttachImageSize-Talk

User notes? : If you use, used or reviewed this recipe, you can add your name. These statistics appear in the Cookbook listings and will help newcomers browsing through the wiki.