Using Imagecache on external images

Filed under:

Recently we rebuilt a site for a client that was using Flickr to host a whole slew of product images for his website. Now I know what you’re thinking. Hosting images for you website somewhere other than your Drupal install seems a little bit silly, your website now depends on your server being up and it also depends on Flickr’s servers being up. That being said, Flickr does provide quite an extensive API for accessing your images and it’s made even easier with Dan Coulter’s phpFlickr class.

Aside from this though, we wanted to be able push all of the product images through Imagecache in order that we could get consistently sized images for our page layouts.

For those of you that don’t know, Imagecache is a wonderful Drupal module that allows you to define image processing presets (ie scale, crop, colour shift plus lots more). The module then takes your image, processes it according to your preset, and then stores this new copy on the server ready to placed on the page when it is called. This allows you to do some neat things with images without having to upload multiple versions of the same image. You can assign an image an Imagecache preset in various places in the config or you can call it in your code like this:

  1. print theme('imagecache', 'preset_namespace', $image_filepath, $alt, $title, $attributes);

However, herein lies the problem for us trying to use this on images that we have pulled in from Flickr. Imagecache does not allow you to run a preset on an external image, the image has to be inside your Drupal install. So this is where the fun starts.

We decided to write a function that would go out to Flickr and pull in our images and store them in a folder on our server. And it looks a little something like this:

(Read the inline comments for a basic explaination of what the code does)

  1. function marmalade_helper_download_from_flickr($flickr_image_id) {
  2.   $flickr = new phpFlickr('6a332a7d86cea24360a71dde09c22c71');
  3.   $sizes = $flickr->photos_getSizes($flickr_image_id);
  4.   $largest_available_size = array_pop($sizes);
  5.   //Check if the containing folder exists -- if not, create it.
  6.   $dir = file_create_path() .'/flickr-originals';
  7.         if (!file_check_directory($dir)){
  8.                 mkdir($dir, 0775, true);
  9.         }
  10.   // Get the image from Flickr
  11.   $url = $largest_available_size['source'];
  12.   //set up the local file name
  13.   $ext = '.' . 'jpg'; // This should get everything after the last full-stop in the above $url, but hardcoding for now
  14.   $src = file_create_path() . '/flickr-originals/' . $flickr_image_id . $ext;
  15.         $result = drupal_http_request($url);
  16.         $code = floor($result->code / 100) * 100;
  17.         $types = array('image/jpeg', 'image/png', 'image/gif');
  18.         if ($result->data && $code != 400 && $code != 500 && in_array($result->Content-Type, $types)) {
  19.                 $src = file_save_data($result->data, $src);
  20.                 return TRUE;
  21.   }
  22.         else {
  23.                 //if we are unsuccessful then log a message in the watchdog
  24.                 watchdog('flickr', 'The image '. $url . ' could not be retrieved');
  25.                 return FALSE;
  26.         }
  27. }

We then wrote a little wrapper function for the Imagecache call which basically checks if the image exists locally, if it doesn’t then it calls the marmalade_helper_download_from_flickr() to go and get it from Flickr. Once the image is down from Flickr, or if it was already there, it runs the Imagecache theme call.

  1. function marmalade_helper_flickr_imagecache($flickr_image_id, $imagecache_preset) {
  2.   $local_image_url = file_directory_path() . '/flickr-originals/' . $flickr_image_id . '.jpg';
  3.   if (!file_exists($local_image_url)) {
  4.     impact_helper_download_from_flickr($flickr_image_id);
  5.   }
  6.   if (file_exists($local_image_url)) {
  7.     return theme('imagecache',$imagecache_preset, $local_image_url);
  8.   }
  9.   else {
  10.     return '<span>Image could not be found</span>';
  11.   }
  12. }

We were then able to print an image on the page by calling this function. All we have to do is provide it with a Flickr image id and the Imagecache preset we want to use.

  1. $image = marmalade_helper_flickr_imagecache($photo_id, 'product_page_large');
  2. print $image;

I hope this helps someone :) Leave a comment and let us know what you think!!

Comments

Add new comment

great

great site vigrx

great!

Our coach outlet store online and coach bags on sale is a professional offer coach brand like coach purse, coach bags outlet and the price is reasonable because we have our coach factory and here you also find the coach outlet store online. I am sure it will save you a lot of time and money if you buying from us.

great!

Handbags like coach handbags act as important role in our life. The coach bags here mean the trend. If you are interested in fashion, you should not miss our website. Make sure you will find something what you want. The coach shoes are really beautiful and cheap. Why not have your coach handbags now?

That's something that I want,

That's something that I want, thanks! Very helpful. free advertising |employment|latex mattress

Thanks for very useful tips

Thanks for very useful tips and guidelines - very effective I must admit!

Tim (writing for students and essays)

Thanks for the very

Thanks for the very interesting information. I like to read such type of articles.
detox products

re

It's the best article on that subject I ever met in the web. I've read some posts here and this essay I like most of all. Good job. Thanks.

location automobile

Happy to see your blog as it is just what I’ve looking for and excited to read all the posts. I am looking forward to another great article from you. After skimming through your website

location automobile

Citarum River amid in West

Citarum River amid in West Java pass4sure VCP-410, Indonesia is maybe the world's a lot of attenuated river pass4sure 640-802. The river is heavily attenuated by animal activity. The account beneath appearance the river like a sea of garbage.Business Logo

Re:

I found this a bit too late. :( I really needed it few days ago for best scar removal cream . But now it will be in my list.

is this working fime??

1.
$image = marmalade_helper_flickr_imagecache($photo_id, 'product_page_large');
2.
print $image;

-------------
Add glamour to your wardrobe through the dazzling collection of Evening Dresses , prom dresses , evening gowns, white cocktail dresses online.core 2 duo , Coupon Codes , school grants,red microwave, dresser furniture, evening dresses blog

aetge

The timberland boots credo is to create excellence. The adidas shoes has always represented a special status. The ed hardy create a feeling of decadent erosion. The nike shox is a new technology, similar to the column. All of the above are my love. The ed hardy tank with rose,skull is so well. The white nike shox turbo is my selection. So are the adidas adicolor. I choose, I like.

Thanks for you sharing! We

Thanks for you sharing! We are the famous laptop adapter supplier and laptop battery supplier. Our main products are various rechargeable laptop battery and laptop adapter compatible with brand laptops, including IBM, COMPAQ, HP, DELL, SONY, ACER, ASUS, APPLE, and TOSHIBA and so on. Because we are the laptop battery manufacturer and laptop adapter manufacturer, we could wholesale laptop battery and wholesale laptop adapter. Our laptop battery factory and laptop adapter factory are seated in china, so we sell the laptop battery china and laptop adapter china. We also know the laptop could be called notebook, so the products we sell could be also called the notebook battery and notebook adapter. we could be called the notebook battery supplier and notebook adapter supplier. We welcome you to visit our notebook battery manufacturer and notebook adapter manufacturer.

Got it working by installing Activity Stream

Hi - just to let you know - it picked up the class when I installed the activity stream module. Still dont quite understand why Flickr API didn't work:

Am receiving a rather nasty error message now:

warning: array_pop() [function.array-pop]: The argument should be an array in /Users/ruski/Sites/Aquia/acquia-drupal/sites/all/themes/wilderness/template.php on line 472.

I fear it might be beyond me - this one, for now...

I am attempting to output a series of embedded images into a view block - that I am preprocessing because I need to change the alt att - for my javascript gallery to work...

Such is my preprocess:


function wilderness_preprocess_semanticviews_view_fields__apple_gallery__page_1(&$vars) {

$row = $vars['row'];

$photo_id = ($row->node_data_field_photo_url_field_photo_url_value);
$stuff = unserialize($row->node_data_field_photo_url_field_photo_url_data);
$imagetitle = $data['title'];

$vars['flickrfield'] = $image = wilderness_helper_flickr_imagecache($photo_id, 'apple-thumb', 'thumbnail', $imagetitle);

$vars['thumb'] = theme('imagecache', $namespace, $path, 'thumbnail', $title, $attributes);

}

meaning that I doctored your code to include the thumbnail argument:

function wilderness_helper_flickr_imagecache($flickr_image_id, $imagecache_preset, $alt, $title) {
$local_image_url = file_directory_path() . '/flickr-originals/' . $flickr_image_id . '.jpg';
if (!file_exists($local_image_url)) {
wilderness_helper_download_from_flickr($flickr_image_id);
}
if (file_exists($local_image_url)) {
return theme('imagecache',$imagecache_preset, $local_image_url, $alt, $title, $attributes);
}
else {
return 'Image could not be found';
}
}

Many thanks for the kick start...

A problem

Firstly I like the name of your site - now I've got that out the way...

Bit of a drupal noob and this is testing me to my limit! I am getting this error when implementing the code. I have pasted the functions into my template.php - inserting my key etc... but it can't seem to find the phpFlickr class :(

Fatal error: Class 'phpFlickr' not found in /Users/ruski/Sites/Aquia/acquia-drupal/sites/all/themes/wilderness/template.php on line 470

I have the flickr API installed and my keys and secret are installed. Inside the API directory sites a phpFlickr directory with the class in it.

I have aslo enabled the flickr module and placed it in their as well for good measure after getting this error...

Can you enlighten me?

You need to include the

You need to include the phpFlickr class by adding this to the top of your module:


require_once("phpflickr/phpFlickr.php");

So far, I managed to go

So far, I managed to go though only some of posts you discuss here, but I find them very interesting and informative. Just want say thank you for the information you have shared. Regards James

Typo??

Line 4 of function marmalade_helper_flickr_imagecache

-> impact_helper_download_from_flickr($flickr_image_id);

I think should read:

-> marmalade_helper_download_from_flickr($flickr_image_id);

Not a big deal but it might throw some of your readers off.

Thanx for grat site

I really like your post. Does it copyright protected?

Hi, good post. I have been

Hi, good post. I have been wondering about this issue,so thanks for posting. I’ll definitely be coming back to your site.

This is really a well laid

This is really a well laid out website. I like how you have presented your information with excellent detail. Keep up the great work here.

Good stuff and deja vu!

This reminded me of a very similar situation last year where I tried to get the "local copy" functionality for Image Cache's sake into the Embedded Media Field module, which also utilises Flickr (amongst other things) as a possible source.

Hard to beat Flickr as an image manager, eh? Nice solution!

Useful!

Hi guys! This is very useful, as I was looking into such functionality. I'm going to go through the code carefully, and was thinking of integrating it in the node creation/posting process, maybe with a CCK field, which takes a Flickr photo URL and then applies your magic on it!

Soroush < http://sorou.sh >

Interested?

We're committed to forming long-term relationships with our clients, so you can be sure that we will be around in the future to support your site and grow with your needs.

get a free quote