4

I need to make two links for an image, one link points to a low res version the other to the original file.

I'm creating the link for the low res with image_style_url

<?php print image_style_url('img-lib', $data->field_field_photo[0]['raw']['uri']) ?>

How can I print out the filesize of the image with img-lib style?

7
+50

You can get the size of the original image easily:

$size = filesize($data->field_field_photo[0]['raw']['uri']);

But the size of an image file behind a derivative path is impossible to get reliably. The files aren't generated until the URL is first visited, so the file may simply not exist yet.

For those that do already exist, you can use image_style_path():

$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}

If it's 'mission-critical' to get the file size, you can always force-create the derivative there and then with image_style_create_derivative():

$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}
else {
  if (image_style_create_derivative('img-lib', $data->field_field_photo[0]['raw']['uri'], $path) === TRUE) {
    $size = filesize($path);
  }
}

if (!isset($size)) {
  // Something went wrong creating the derivative...
}

It's worth noting that you shouldn't do all (or any really) of the above directly in a template file. Instead, move your logic out to a preprocess function and pass variables in.

And if you're looking for full-on 'best practice', instead of accessing the field data directly through the array (e.g. $data->field_field_photo[0]['raw']['uri']), prefer field_get_items() for procedural-style, or an EntityMetadataWrapper if you're comfortable with OO.

  • I've learned a lot from this and it works, thank you! – Bálint Deáki Mar 17 '14 at 8:06
  • No problem @BálintDeáki, glad it helped :) – Clive Mar 18 '14 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.