Files


$image Properties (in addition to those in $file)

$image->width

Introduced in Version 2.0

Description

Width of image, in pixels

Using image width inside img-tag:

// Grab the first image from images-field
$img = $page->images->first();

// Echo it with width and height like we did in 90's 
echo "<img src='$img->url' alt='' width='$img->width' height='$img->height' />";

Notice that images is just a normal field, although it is on default profile. When your image-field is set to contain more than one image, then it becomes WireArray. This means you can't access $page->images->width directly, since ProcessWire doesn't understand which image width you are looking for. Even if you have only one image uploaded, you need to be specific about which image you mean, hence the usage of method first() in above example.

Here is another example with image field called my_photo which is set to accept only one image:

echo "See, my face is {$page->my_photo->width} pixels wide"; 

Very common use case is looping all the images and outputting their attributes somehow:

foreach($page->photos_about_my_kids as $photo) {
    $thumb = $photo->width(200); // Make them 200 pixels wide
    echo "<img src='$thumb->url' width='$thumb->width' height='$thumb->height' alt='$thumb->description' />";
}

Of course you can use width-property for many other occasions too. Maybe output some inline css in some cases. Here we want our .header elements to have twice the width our $img has:

$headerWidth = $img->width * 2;
echo "<style> .header {width: {$headerWidth}px;} </style>";


Related

Post Comment