After trying for many years to maintain a personal blog, with many starts and stop, I have given up. I realized I don't *want* to write personal thoughts on the web. Instead, I've been messing around with my own custom tumblelog scripts. I use delicious, Flickr, last.fm, and other services that I want to aggregate in one place. I know there are services out there that do this already, but I thought rolling my own would be a good excuse to dust off my PHP skills.

One feature I wanted to have was the ability to grab images from other sites, re-size them, and copy them to my local server.   Nothing special, but very useful.

$remote_image = "some_img_url";

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $remote_image);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);

$file_as_string = curl_exec($ch);
$new_file_name =  substr(strrchr($remote_image, "/"), 1);
$path_to_img = '/path/to/image/folder/'.$new_file_name;

resizeImage($file_as_string, 600, $path_to_img);

curl_close($ch);

function resizeImage($img_as_string, $max_width, $dst){
   $image = imagecreatefromstring($img_as_string);
   $orig_width = imagesx($image);
   $orig_height = imagesy($image);

   $width = $orig_width;
   $height = $orig_height;

   if ($orig_width > $max_width){
      $height = ($orig_height * $max_width) / $orig_width;
      $width = $max_width;
   }			

   $image_p = imagecreatetruecolor($width, $height);

   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $orig_width, $orig_height);

   imagejpeg($image_p, $dst, 100);
}

What this script does is:

  • using curl, grab the image remotely (as a string)
  • parse the name of the image, create a string that represents the server path to copy the image to
  • proportionally resize the image if it's wider than 600 pixels
  • save it

This code can be easily modified to resize the image if it's taller than x pixels.  I made a very simple form, so now I can supply the script with the image url, and it takes care of the rest.

Related posts:

  1. 37Signals and PHP?