Snipe.Net Geeky, sweary things.

Dynamic thumbnailing with PHP and Imagemagick

D

This code formatting is a little off, since the WYSIWG editor seems to have eaten part of it. Sorry.

<?php

/* ———————————————- */
/* ———— BEGIN PHP SNIPPET —————-*/
/* ———————————————- */
// specify your file details
$current_file = “image.jpg”;
$max_width = “150”;

// get the current info on the file
$current_size = getimagesize($current_file);
$current_img_width = $current_size[0];
$current_img_height = $current_size[1];
$image_base = explode(“.”, $current_file);

// this part gets the new thumbnail name
$image_basename = $image_base[0];
$image_ext = $image_base[1];
$thumb_name = $image_basename.“-th.”.$image_ext;

// determine if the image actually needs to be resized
// and if it does, get the new height for it
if ($current_img_width > $max_width) {
$too_big_diff_ratio = $current_img_width/$max_width;
$new_img_width = $max_width;
$new_img_height = round($current_img_height/$too_big_diff_ratio);

// presto chango alacazam
$make_magick = system(“convert -geometry $new_img_width x $new_img_height $current_file $thumb_name”, $retval);

// let us know if it worked or not
if (!($retval)) {
echo
“Thumbnail created  -“.$thumb_name;
} else {
echo
“Oops – no dice! Script failed cuz your momma doesn’t love you.”;
}
} else {
echo
“No need to resize! You’re perfect just the way you are.”;
}

?>

About the author

snipe

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

By snipe
Snipe.Net Geeky, sweary things.

About Me

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

Get in Touch