Get total number of pixels, size in megapixels and aspect ratio based on image width and height?

Sure – php can definitely handle simple math like this. All you’d have to do is reference the numbers coming back from the wp_get_attachment_image_src call:

<?php

if ( has_post_thumbnail()) {
 $full_image_info = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
 $img_h = $full_image_info[1];
 $img_w = $full_image_info[2];

 $total_pixels =  $img_w * $img_h ;

 $megapixels = round($total_pixels)
 /* see http://at2.php.net/manual/en/function.round.php -- 
    they get into the details of this method there. There's also number_format() as an option. */

 $ratio = $img_w / $img_h;

From there, you can do what you like with $total_pixels, $megapixels, and $ratio. And of course, you could wrap any of these math operations up as a function by putting something like this, for example, in your functions.php:

function get_total_pixels() {

  if ( !has_post_thumbnail()) { return 'Error - no image!'; }
  else {
    $image_info = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    $img_h = $image_info[1];
    $img_w = $image_info[2];

    $total_pixels =  $img_w * $img_h ;
    return $total_pixels;
  }
}

and then calling <?php echo get_total_pixels(); ?> in your template file (inside the loop).

Leave a Comment