Hi everyone!

I've got user pictures uploaded onto my site through $user->picture, but I want to sometimes display the picture at "full size", sometimes at "thumbnail", and sometimes at "mini" (20x20px) size. Is there an easy way to do this through drupal? [Like something like theme($user->picture,'large') or something like that?]

All help appreciated.

Thanks!

Albert
www.ithou.org

Comments

ajwwong’s picture

So... I'm still trying to format my "user_picture" differently, depending on the context of where it shows up -- for example, I want to have the user_picture be "miniaturized" when it shows up with comments, but *big* when it shows up on the user_profile page.

If anyone has any ideas, I'd still love to hear them...

Anyhow, right, now I've been looking at these different functions... apparently, you can possibly theme the user_picture differently for node, user, block... tho-- I'm still figuring out how this all works... for example... I've seen these kinds of functions in code, so there may be a way of doing this after all... :-)

theme('user_picture',$node);
theme('user_picture',$user);
theme('user_picture',$account);
theme('user_picture',$block);
theme('user_picture',$comment);

I'll post here if I figure it out.

Albert
www.ithou.org

bradlis7’s picture

I like the idea... Maybe you could start a feature request, to where the theme can decide what it wants. You might take a look at image.module, because it uses a thumbnail, medium size, and the original size for images, and other sizes are configurable.

Another option I'd like to see is to allow the user's picture to be displayed in certain node types, as in the forum only. This can be done with the theme, but it's a hack, and not one I like to use. That's a whole new topic though...

--
Bradlis7.com | Churchofchristnet

ajwwong’s picture

and it looks as if the image module actually loads up the entire picture, and then resizes it -- so I have decided that that might be a bit too bandwidth intensive to load up the entire picture, especially if all I want is a mini version of it.

So, currently I'm looking into the following strategy: I am trying to save three different copies of the user_picture -- a full-size , a regular one for the icon, and a mini version of it -- during the user_picture_validate function -- i.e., when the user first uploads the picture. However, I am having a difficult time with it.

it seems as if once you use file_save_upload, you cannot use it again -- that is, once you have "saved" the file that you've uploaded, you cannot "re-save" it-- for example, at a different magnification. if anyone has any ideas on how to "re-save" a file that you have already "saved" through file_save_upload, I would love to hear them.

Thanks,

Albert
www.ithou.org

In case anyone is interested in this, here is the current state of my (non-functioning) code-- this is a hack to user.module's user_picture_validate function:

function user_validate_picture($file, &$edit, $user) {
  global $form_values;
  // Initialize the picture:
  $form_values['picture'] = $user->picture;

  // Check that uploaded file is an image, with a maximum file size
  // and maximum height/width.
  $info = image_get_info($file->filepath);
  list($maxwidth, $maxheight) = explode('x', variable_get('user_picture_dimensions', '85x85'));

  if (!$info || !$info['extension']) {
    form_set_error('picture_upload', t('The uploaded file was not an image.'));
  }
  else if (image_get_toolkit()) {
    image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
  }
  else if (filesize($file->filepath) > (variable_get('user_picture_file_size', '30') * 1000)) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum file size is %size kB.', array('%size' => variable_get('user_picture_file_size', '30'))));
  }
  else if ($info['width'] > $maxwidth || $info['height'] > $maxheight) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'))));
  }

  if (!form_get_errors()) {
// **************my hack begins here -- ajwwong *************************
    $file_icon = $file; // I am storing a copy of $file for the different sizes of $user->picture I want to eventually manipulate
	$file_mini = $file;   
//These next two lines were here before, and work OK -- that is the file gets saved appropriately as your regular old user picture-- ajwwong */
    if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picture-'. $user->uid . '.' . $info['extension'], 1)) {
      $form_values['picture'] = $file->filepath;
//*however, when I try to scale the images and add these next lines below to create *different sized* user pictures-- for some reason, the file does not ultimately get saved --ajwwong
	  
	  $file =  $file_icon;
	  $maxwidth_icon = 50;
	  $maxheight_icon = 50; 
	  image_scale($file->filepath, $file->filepath, $maxwidth_icon, $maxheight_icon);	  
	  $file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/pictureicon-'. $user->uid . '.' . $info['extension'], 1);
	  /*print_r($file_icon);
	  print_r($file_mini);
	  print_r($file);*/
	
	  $file = $file_mini;
      $maxwidth_mini = 20;
	  $maxheight_mini = 20; 
	  image_scale($file->filepath, $file->filepath, $maxwidth_mini, $maxheight_mini);
	  $file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picturemini-'. $user->uid . '.' . $info['extension'], 1);
      /*print_r($file_icon);
	  print_r($file_mini);
	  print_r($file);*/
// Adding these lines above to create *different sized* user pictures!! but it does not actually save the pictures correctly, or at all. ajwwong 4.23.06	  */
// **************my hack ends here -- ajwwong *************************
	  
	  
    }
    else {
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => '<em>'. variable_get('user_picture_path', 'pictures') .'</em>')));
    }
  }
}
bradlis7’s picture

It makes sense that file_save_image would move the file, because it would leave a dangling file if not.

I think changing this line,

  else if (image_get_toolkit()) {
    image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
  }

to make it scale the other two images to a new destination beforehand would do the job.

  else if (image_get_toolkit()) {
    /* added */
    $maxwidth_icon = 50;
    $maxheight_icon = 50;
    image_scale($file->filepath, variable_get('user_picture_path', 'pictures') .'/pictureicon-'. $user->uid . '.' . $info['extension'], $maxwidth_icon, $maxheight_icon);
    $maxwidth_mini = 20;
    $maxheight_mini = 20;
    image_scale($file->filepath, variable_get('user_picture_path', 'pictures') .'/picturemini-'. $user->uid . '.' . $info['extension'], $maxwidth_mini, $maxheight_mini);

    /* kept same */
    image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
  }

Here's a cleaned up version:

function user_validate_picture($file, &$edit, $user) {
  global $form_values;
  // Initialize the picture:
  $form_values['picture'] = $user->picture;

  // Check that uploaded file is an image, with a maximum file size
  // and maximum height/width.
  $info = image_get_info($file->filepath);
  list($maxwidth, $maxheight) = explode('x', variable_get('user_picture_dimensions', '85x85'));

  if (!$info || !$info['extension']) {
    form_set_error('picture_upload', t('The uploaded file was not an image.'));
  }
  else if (image_get_toolkit()) {
    /* added */
    $maxsize_icon = array('w'=>50,'h'=>50); //clean up
    image_scale($file->filepath, variable_get('user_picture_path', 'pictures') .'/pictureicon-'. $user->uid . '.' . $info['extension'], $maxsize_icon['w'], $maxsize_icon['h']);
    $maxsize_mini = array('w'=>20, 'h'=>20);
    image_scale($file->filepath, variable_get('user_picture_path', 'pictures') .'/picturemini-'. $user->uid . '.' . $info['extension'], $maxsize_mini['w'], $maxsize_mini['h']);
    /* end add */

    image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
  }
  else if (filesize($file->filepath) > (variable_get('user_picture_file_size', '30') * 1000)) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum file size is %size kB.', array('%size' => variable_get('user_picture_file_size', '30'))));
  }
  else if ($info['width'] > $maxwidth || $info['height'] > $maxheight) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'))));
  }

  if (!form_get_errors()) {
    if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picture-'. $user->uid . '.' . $info['extension'], 1)) {
      $form_values['picture'] = $file->filepath;
     
    }
    else {
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => '<em>'. variable_get('user_picture_path', 'pictures') .'</em>')));
    }
  }
}

I haven't tested it, but logically, I think it will work. It copies the image at the same time as resizing it.
--
Bradlis7.com | Churchofchristnet

ajwwong’s picture

that's *way* beyond the call of duty... thanks so much bradlis! I'll definitely give that a shot and report back! :-) It looks really good so far...

Thanks again!

Albert
www.ithou.org

ajwwong’s picture

I'm getting the following warning when I try the code above...

Warning: imagejpeg(): Unable to open 'pictures/pictureicon-6.jpg' for writing in /home/ithou/public_html/includes/image.inc on line 300

Warning: imagejpeg(): Unable to open 'pictures/picturemini-6.jpg' for writing in /home/ithou/public_html/includes/image.inc on line 300

Warning: Cannot modify header information - headers already sent by (output started at /home/ithou/public_html/includes/image.inc:300) in /home/ithou/public_html/includes/common.inc on line 265

I've checked my permissions in my "pictures" directory, and it's set to 777 -- read, write, execute -- so I don't think it's a permissions issue.

Hmmm... well, I'll try the file_move idea you wrote about in the other post. Thanks again!

Albert
www.ithou.org

havran’s picture

bradlis7’s picture

So, an easy work around might be to copy the file to the necessary location, and resize it, using the same $source and $destination.

$icon = $file; //file_copy changes the value of the variable
if(file_copy($icon, variable_get('user_picture_path', 'pictures').'/pictureicon-'. $user->uid . '.' . $info['extension']))
  image_scale($icon->filepath,  $icon->filepath, $maxsize_icon['w'], $maxsize_icon['h']);

--
Bradlis7.com | Churchofchristnet

ajwwong’s picture

That did it bradlis!!

Perfectomundo....

Thanks so much... that's perfect... !!

Blessings to you,

Albert
www.ithou.org

ajwwong’s picture

4.7 tested only

Here's the steps... much thanks to bradlis for guiding the way... it actually involves a hack to user.module... but, well, ya only live once... There might be a better way... -- in fact, on second thought, I should have perhaps made more use of image.module as bradlis had initially suggested, but I couldn't figure out the _produce_image_derivatives functionality of that module... If I had to do it so that it was really clean, I might have tried to create a new database linking $uid and $nodeid where $nodeid is the $node of the picture that is the $user's preferred avatar... -- but, well, I still don't know how to set things like that up... and this works too... even if it involves a hack to core...

So, w/o further ado here it is...

Step 1. Modify user.module's function user_validate_picture into what's listed below:

function user_validate_picture($file, &$edit, $user) {
  global $form_values;
  // Initialize the picture:
  $form_values['picture'] = $user->picture;

  // Check that uploaded file is an image, with a maximum file size
  // and maximum height/width.
  $info = image_get_info($file->filepath);
  list($maxwidth, $maxheight) = explode('x', variable_get('user_picture_dimensions', '85x85'));

  if (!$info || !$info['extension']) {
    form_set_error('picture_upload', t('The uploaded file was not an image.'));
  }
  else if (image_get_toolkit()) {
    /* added */
    $maxsize_icon = array('w'=>175,'h'=>175); //clean up
	$icon = $file; //file_copy changes the value of the variable
	if (file_copy($icon, variable_get('user_picture_path', 'pictures').'/pictureicon-'. $user->uid . '.' . $info['extension'], $replace = FILE_EXISTS_REPLACE)) {
      image_scale($icon->filepath,  $icon->filepath, $maxsize_icon['w'], $maxsize_icon['h']);
    } 
    $maxsize_mini = array('w'=>20, 'h'=>20);
	$mini = $file;
    if (file_copy($mini, variable_get('user_picture_path', 'pictures').'/picturemini-'. $user->uid . '.' . $info['extension'], $replace = FILE_EXISTS_REPLACE)) {
      image_scale($mini->filepath, $mini->filepath, $maxsize_mini['w'], $maxsize_mini['h']);
    } 
	/* end add */

    image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight);
  }
  else if (filesize($file->filepath) > (variable_get('user_picture_file_size', '30') * 1000)) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum file size is %size kB.', array('%size' => variable_get('user_picture_file_size', '30'))));
  }
  else if ($info['width'] > $maxwidth || $info['height'] > $maxheight) {
    form_set_error('picture_upload', t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'))));
  }

  if (!form_get_errors()) {
    if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picture-'. $user->uid . '.' . $info['extension'], 1)) {
      $form_values['picture'] = $file->filepath;
   
    }
    else {
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => '<em>'. variable_get('user_picture_path', 'pictures') .'</em>')));
    }
  }
}

Step 2.

Add this to the end of your template.php file for the template override:

function phptemplate_user_picture($account, $size = '') {
  return _phptemplate_callback('user_picture', array('account' => $account, 'size' => $size));
}

Step 3.

Add the file user_picture.tpl.php in your active template folder and put the following into it:

  if (variable_get('user_pictures', 0)) {
    if ($account->picture && file_exists($account->picture)) {
//add these lines in case of icon or mini
      if ($size == 'icon') {
	    $picture = 'files' . variable_get('user_picture_path', 'pictures').'/pictureicon-'. $account->uid . '.jpg';
		$picture = file_create_url($picture);
      }
	  else if ($size == 'mini') {
	    $picture = 'files' . variable_get('user_picture_path', 'pictures').'/picturemini-'. $account->uid . '.jpg';
        $picture = file_create_url($picture);
      }
	  else {
        $picture = file_create_url($account->picture);
		print_r($picture);
	  }
    }
    else if (variable_get('user_picture_default', '')) {
      $picture = variable_get('user_picture_default', '');
    }

    if (isset($picture)) {
      $alt = t('%user\'s picture', array('%user' => $account->name ? $account->name : variable_get('anonymous', 'Anonymous')));
      $picture = theme('image', $picture, $alt, $alt, '', false);
	  if (!empty($account->uid) && user_access('access user profiles')) {
        $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE);
      }

      print_r("<div class=\"picture\">$picture</div>");
    }
  }
  

Now, anytime you want an userpicture of your preset size, you call the function:
theme('user_picture', $user , $size) ...

For example....

print theme('user_picture',$my_user, 'icon');

Good luck!

Only for 4.7

Albert
www.ithou.org

hba’s picture

I made a patch out of this and added it to http://drupal.org/node/60987. It needs more work, though...

bombaclot’s picture

What do you think would be the best way to get more images on the user profile?
Thanks

bradlis7’s picture

I think that would have to be done with a full module. Make a request as a new topic, and I bet you'll get a lot of attention.
--
Bradlis7.com | Churchofchristnet

Annika’s picture

Hi,

I first tried to install the patch but MAC OSX's terminal claimed it was bad code that ended halfway. Might also have been me being a klutz. Command line is not one of my better features.

However, I used the code posted above instead and now I've got two problems;

1) The user image I'm testing with don't resize when I use $icon or $mini in the user_profile.tpl.php. Am I supposed to determine image sizes anywhere else than in the snippet above or have any other modules installed? I have GD and the image_module installed if that matters.

2) I get the image path written out everywhere the image appears. At a look at the source code it says;

<div class="content">http://quicksilver.local/fixxxa/filer/medlemsbilder/picture-1.gif<div class="picture"><a href="/fixxxa/?q=medlemmar/annika" title="Titta på användarprofilen."><img src="//quicksilver.local/fixxxa/filer/medlemsbilder/picture-1.gif" alt="Annikas bild" title="Annikas bild" /></a></div>

The code in the user_profile.tpl.php is

<?php
  if($user->picture) {
    print theme('user_picture', $user, '$mini');
  }
?>

I haven't the faintest idea from where that path comes from. I've redone the process twice to be certain there are no errors, but alas still no success.

I hope somebody can shred some light on this.

Oh, and I'm using Drupal 4.7.2 with a modded Friends Electric theme.

:-)

Ayza

netceo’s picture

I am getting the image path written on top of the image too.. can somebody please help?
NetCEO

Anonymous’s picture

I am also getting the image path, but only on images where I haven't replaced the picture with the new code.

I also don't exactly know how to write it. The example code:

print theme('user_picture',$my_user, 'icon');

results in everyone having the default user picture. How do I change '$my_user' to show the picture for that user?

Thanks,
txcrew

ajwwong’s picture

This is a snippet I wrote a while ago with help from bradlis... and it's kinda receded into the back of my memories... so I'm not sure if this is going to be helpful, but...

Anyhow, these are my best answers:

@Ayza, netceo: I think you need to reupload the pictures, possibly, and then you should get the things to resize? Anyhow, that's the only thing I can think of.

BTW, the other thing is, there is a known bug with *gif* files. For some reason it's not working with gifs, only jpegs... I think... I tried to figure this piece out and maybe I'll get there someday, but I'm kinda swamped right now with trying to get exim set up on my machine.

@txcrew: honestly, i don't remember , but I think $my_user becomes something like the number [or the name? I forget] of the user whose picture you're trying to show.

Good luck everyone!

Albert
www.ithou.org

Annika’s picture

Thanx Albert,

I think it's must be the gif bug. I didn't know about it. I'll redo the images in jpeg.

Patrick Nelson’s picture

For anyone else reading this, the correct thing to replace $my_user with is $node (or $comment for comments).

Regards

Patrick Nelson
www.vcommunity.org.uk

EnekoAlonso-1’s picture

Hello all,

I think this mod is a very good idea. I don't understand why drupal doesn't do it by itself yet, or why theres is no module for this.

Either way, I don't like at all to modify drupal's release files because that stops me to upgrade when a new release is available. So I was thinking, what about creating the resized images via cron? It will be a hook which would check if the small images doesn't exist or if the user picture has been updated (date is newer than thumbs), and the create or recreate the small ones.

That way we will have a lag between a picture modification and cron update, but will be way cleaner.

Any ideas of how to implement this? I just don't have time right now, and I would appreciate any code! :)

Annika’s picture

Sorry I can't help though. My knowledge about Cron basically stops at knowing how to spell it.

:-)

Ayza

EnekoAlonso-1’s picture

Based on the code shown above (very good job, ajwwong), I have created what will do the same, but without touching a single line of Drupla's code. This means we don't need to modify user.module file.

The way I have done it, instead of creating thumbnails when user uploads his picture, pictures are resized on demand, if they haven't been resized previously or if user's image has changed.

Step 1: Add this to the end of your template.php (identical to previous 2nd step):

<?php
  function phptemplate_user_picture($account, $size = '') {
    return _phptemplate_callback('user_picture', array('account' => $account, 'size' => $size));
  }
?>

Step 2: Add the file user_picture.tpl.php in your active template folder and put the following into it:

<?php
  if (variable_get('user_pictures', 0)) 
  {
    if ($account->picture && file_exists($account->picture)) 
    {
      if ($size == 'node') // 80x80
      {
        $info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picture-' . $account->uid . ".80." . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, 80, 80);
        } 
        $picture = file_create_url($newpicture);
      }
      else if ($size == 'comment')  // 48x48
      {
        $info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picture-' . $account->uid . ".48." . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, 48, 48);
        } 
        $picture = file_create_url($newpicture);
      }
      else if ($size == 'mini')  // 20x20
      {
        $info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picture-' . $account->uid . ".20." . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, 20, 20);
        } 
        $picture = file_create_url($newpicture);
      }
      else
      {
        $picture = file_create_url($account->picture);
      }
    }
    else if (variable_get('user_picture_default', '')) {
      $picture = variable_get('user_picture_default', '');
    }

    if (isset($picture)) {
      $alt = t('%user\'s picture', array('%user' => $account->name ? $account->name : variable_get('anonymous', 'Anonymous')));
      $picture = theme('image', $picture, $alt, $alt, '', false);
      if (!empty($account->uid) && user_access('access user profiles')) {
        $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE);
      }

      print_r("<div class=\"picture\">$picture</div>");
    }
  }
 
?>

Of course the code can be modified for diferent image sizes and even better! It would be very easy to modify it to allow passing the final size in pixels (instead of 'node', comment' and 'mini') and get images at runtime of any size.

I hope you like it! For a demonstration, check out this pages and compare the different picture sizes:

Enjoy!

ajwwong’s picture

Haven't had a chance to try this out, but this looks like a very elegant solution! I think this should definitely be a candidate for the template snippets handbook.

Congrats, EnekoAlonso!

Albert
www.ithou.org

Anonymous’s picture

Thanks for this wonderful bit of code.

I'm trying to implement it in my site right now. How exactly do I call it in my theme??

Please let me know when you get a chance.

Thanks,
txcrew

EnekoAlonso-1’s picture

as ajwwong suggested:

print theme('user_picture',$my_user, 'icon');

You can put that code in you comment.tpl.php template or in your node.tpl.php template, or instead use it in any php page you create on your site.

ajwwong’s picture

I can confirm that EnekoAlonso's code works, beautifully.

I should say that for some reason, when I chose sizes for my user pictures that were **larger** than what I was actually uploading, e.g., a size of 160x250 when I was only uploading a picture that was 100x120, the script didn't seem to work for the **large** size -- and didn't update the larger picture, even at a smaller sizing. However, I did the following small workaround, as you can see in the example below for the user size 'icon'. YMMV

Additionally, I added some code to make one of the images "square" [and actually slightly centered high].... this is my user size 'tile'.

I'm listing it here for posterity. Good luck all.

[For use in the user_picture.tpl.php file]

  if (variable_get('user_pictures', 0)) 
  {
    if ($account->picture && file_exists($account->picture)) 
    {
      if ($size == 'icon') // 160x250  This is a BIG user picture 
      {
        $maxsize_icon = array('w'=>160,'h'=>250);
		$info = image_get_info($account->picture);
		if ($info['height'] < $maxsize_icon['h']) {
		  $maxsize_icon['h'] = $info['height'];
		}
        if ($info['width'] < $maxsize_icon['w']) {
		  $maxsize_icon['w'] = $info['width'];
		}
        $newpicture = dirname($account->picture) . '/pictureicon-' . $account->uid . '.' . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, $maxsize_icon['w'], $maxsize_icon['h']);
        } 
        $picture = file_create_url($newpicture);
      }
      else if ($size == 'tile')  // 50x50 -- this is the *old* default size
      {
        $maxsize_tile = array('w'=>50, 'h'=>50);
		$info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picturetile-' . $account->uid . '.' . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
		/*Adding this to make the tiles square, but ALSO, centered */		  
		    $imageheight = $info['height'];
    		$imagewidth = $info['width'];
		  	$minside = min($imageheight, $imagewidth);
			if ($imageheight > $imagewidth) {
			  $topleftx = 0;
			  $toplefty = (($imageheight - $imagewidth)/4);
			}
			else { 
			  $topleftx = ($imagewidth - $imageheight)/2;
			  $toplefty = 0;
			}
			image_crop($account->picture, $newpicture, $topleftx, $toplefty, $minside, $minside);
        /*end add ajwwong*/
		  
          image_scale($newpicture, $newpicture, $maxsize_tile['w'], $maxsize_tile['h']);
        } 
        $picture = file_create_url($newpicture);
      }
      else if ($size == 'mini')  // 20x20
      {
        $maxsize_mini = array('w'=>20, 'h'=>20);
        $info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picturemini-' . $account->uid . '.' . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, $maxsize_mini['w'], $maxsize_mini['h']);
        } 
        $picture = file_create_url($newpicture);
      }
      else
      {
        $picture = file_create_url($account->picture);
      }
    }
    else if (variable_get('user_picture_default', '')) {
      $picture = variable_get('user_picture_default', '');
    }

    if (isset($picture)) {
      $alt = t('%user\'s picture', array('%user' => $account->name ? $account->name : variable_get('anonymous', 'Anonymous')));
      $picture = theme('image', $picture, $alt, $alt, '', false);
      if (!empty($account->uid) && user_access('access user profiles')) {
        $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE);
      }

      print_r("<div class=\"picture\">$picture</div>");
    }
  }
  

Albert
www.ithou.org

hba’s picture

I cannot get this to work with bluemarine and 4.7. I replace "print $picture" with "print theme('user_picture',$account, 'icon');" in comment.tpl.php and create a user_template.tpl.php with the content above.

I want comment images to be shown as thumbnails, but now no pictures are displayed.

Steel Rat’s picture

I just want the current user module to actually enforce the picture sizes entered in the configuration. I have max dimensions as 150, yet it allows uploads of HUGE images without resizing them.

Steel Rat
Drupal Site: RPGMapShare.com

bobzillaforever’s picture

I'm trying to get this to work in 6.x, and seem to be in over my head. Although, I'm so new to Drupal that I feel over my head everywhere I go.

It would seem that the following code (which I've been putting in my template.php) needs to be modified, as _phptemplate_callback() has been depracated.

  function phptemplate_user_picture($account, $size = '') {
    return _phptemplate_callback('user_picture', array('account' => $account, 'size' => $size));
  }

Anyone else trying to get this to work?

gurukripa’s picture

can u teach me how to make a good user profile in Drupal 5.1
thanks..urs is too good..with all the friends pics etc..
gr8 work

genemcc’s picture

Thanks. (bookmarking)

patchak’s picture

Hi there,

I tried to use this code on my site, but it does not work, the images are not showing?

Is there anyhting I should change like function name for example or any special detail you might have forgot in your instructions?

If I leave the code in the node.tpl.php intact and only insert the code in template.php and user_picture.tpl.php, then it will show the "mini" version of the image. But every time I try to insert the call to another size as suggested in this thread the images do not show at all.

Any ideas?

Thanks

j0k3z’s picture

I just used this code to change the size of my images on my profile page.

How can I also use it in my forum? Im using flatforum and cant get the code to work. It just displays the full size image.

Im my forum template I am calling the picture using "$picture" so what must I change this to in order to display the smaller version?

I tried using the same code that I used in my profile but it wont show a picture.

j0k3z’s picture

has anybody gotten this code to display an image in forums?

BradM’s picture

followed the instructions to the letter, but no image shows up. :(
can anyone get this to work in 5.x version of drupal?

stephencarr’s picture

This working in 5.1 would be really nice.

r.smith’s picture

I tried EnekoAlonso's code in 5.x and it did work for me....

gurukripa’s picture

i tried this..it works..and the effect is nice.
i had code like specified..but it looks like the pics are being resized on demand..and hence the problem..
wld be nice if it was done earlier....and were cached..

the imagecache is not working strangely :(

what did u do exactly ?

thanks in advance

sameersegal’s picture

Hi,

I followed your steps on 5.2 and its working perfectly, except for one thing.
when i hover the mouse over the picture i get "< em > username < /em >'s picture".

How do i resolve this issues??

regards
Sameer

enzipher’s picture

Hey,

I have just tried the user_picture.tpl.php-code and it works without any major problems in 5.2. Concerning the <em> problem I solved it like this, don't know if it's political correct or anything but anyways...

In user_picture.tpl.php I changed %user to $account->name

    if (isset($picture)) {
      $alt = t($account->name.'\'s picture', array('%user' => $account->name ? $account->name : variable_get('anonymous', 'Anonymous')));
      $picture = theme('image', $picture, $alt, $alt, '', false);
      if (!empty($account->uid) && user_access('access user profiles')) {
        $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE);
      }

Hope it helps, and thanks for the original code btw, great work!

--

hook_world() is broken.

dyutiman’s picture

Try something like this

  if (!form_get_errors()) {
    if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picture-'. $user->uid .'.'. $info['extension'], 1)) {
      $form_values['picture'] = $file->filepath;
	  image_scale($file->filepath,  'files/'.variable_get('user_picture_path', 'pictures').'/pictureSmall-'. $user->uid. '.' . $info['extension'], 72, 59);
    }
    else {
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
    }
  }

Otherwise when user will update his old picture, the thumbnail or other versions will not be updated.

lias’s picture

and how does this affect updating? I'm not a coder but would like to understand.

Quint’s picture

(in Drupal 5.1)

I have a similar need. I set up IMCE and FCKeditor and all is working well now, but there's a problem with what the users are doing.

It's beyond the comprehension of my users to resize an image to 500 pixels max dimension, and use jpg 75. Instead they are uploading 5 megapixel images at jpg 92 straight out of the camera. So the images are too big for the screen and a waste of bandwidth (usually around a meg).

What I plan to do, is let them go ahead and upload, and I'll periodically download them from the image directory, resize and compress, and upload them back to the directory.

I'm afraid this might screw up the formatting of the image on the page as set by FCKeditor, but even if it doesn't, I'd love to find an automatic way to do this.

Someone mentioned a cron job a while back. That seemed like a good idea. If Drupal or a module could resize and compress during user upload, that would be Nirvana for me. Any ideas?

Quint

Quint’s picture

WELL WELL WELL

I went to try uploading a giant picture, couldn't, set IMCE permission to "limitless upload", tried again, and voila, there's a an auto-resize tick box next to 'upload'. WOW COOL ... IMCE already does what I wanted to do.

Problem solved.

IMCE, very cool.

Quint

coupet’s picture

Does it work in 5.x ?

----
Darly

Quint’s picture

yeah, I'm in 5.1

Quint
calculator for building stairs -- www.Shalla.Net

SimonVlc’s picture

Do you made any modification? I´m on 5 and can´t make this working.

Kind regards, Simon.

SimonVlc’s picture

Doesn´t matter, I solve it.

I have to make this call in order to pass the $user variable through the node.tpl.php

global $user;

Is this convenient? Is there any other form?

Thanks in advance, Simon.

gurukripa’s picture

pls can u put the full procedure for 5.1
i cant understand..will be really obliged if u can..thanks..

gurukripa’s picture

dear quint

cld u paste the code and process u used to make it work in 5.1

thanks a lot in advance.

Quint’s picture

I didn't notice a reply in this thread, gurukripa. It's been a week now. Have you figured it out? There is no code other than the IMCE module, and some settings. I can dig around for them, but maybe you've figured it out already.

Quint

alynner’s picture

thanks!
(just bookmarking)

yngens’s picture

subscribe...

tried for 5.dev didn't work. though to say frankly i did not get how and where exactly to call the function. tried in every suggested above ways, unfortunately resized pictures did not show up.

droople’s picture

subscribing

scottrigby’s picture

sylvie_n’s picture

This function isn't working for my default pictures?

sylvie_n’s picture

When i hover over the picture i get the reading. i tried dyutiman's code:

  if (!form_get_errors()) {
    if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'profilepics') .'/picture-'. $user->uid .'.'. $info['extension'], 1)) {
      $form_values['picture'] = $file->filepath;
      image_scale($file->filepath,  'files/'.variable_get('user_picture_path', 'profilepics').'/pictureSmall-'. $user->uid. '.' . $info['extension'], 72, 59);
    }
    else {
      form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => variable_get('user_picture_path', 'profilepics'))));
    }
  }

with the replacement of 'pictures' as my pics are stored in /files/profilepics...
i think i've changed it wrongly? (doesn't work)

chadchandler’s picture

I'm also looking for the easiest/most efficient way to resize users pictures (thumbnail) in posts, but a full size picture in the user profile.

lias’s picture

Everything seems to function with the exception of < em > code showing up when you hover over a user picture. How do you get rid of this except to remove the code snippets from template and php theme files?

ONe more question, does this affect users already registered with photos *before* use of this code? Do you have to resubmit profiles to have resizing applied?
thanks.

lias’s picture

?

thepaul’s picture

bookmark

72dpi’s picture

Why not just use clean CSS to resize images?

Since the user image is already cached, why not just use CSS to size the image to whatever region you want.

I have this implemented on comments book & forum. Works perfect.
You just target your div & it's good..

I discussed this here:
http://drupal.org/node/197332

Might be a consideration for someone...

Steel Rat’s picture

Mainly because that's only changing the display size. What's desired is a physical resize of the image, not just a soft resize.

Steel Rat
My Drupal Sites:
RPGMapShare.com
Infinite Ordnance
Malvern Rouge Valley Youth Center

v1nce’s picture

Try out the ImageCache Profiles module.

ImageCache_Profiles module allows you to set user profile pictures that are consistent throughout your site and allows avatars on the user profile pages to be a different size.

Please submit any bug reports or feature requests after giving it a spin.

sylvie_n’s picture

Hey guys,
code works great. Apart from when the size of the image uploaded is smaller than the resized size. Then it fails to work.
How should I adapt the code?
Currently I am using:

  if (variable_get('user_pictures', 0))
  {
    if ($account->picture && file_exists($account->picture))
    {
      if ($size == 'node') // 200x200
      {
        $info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picture-' . $account->uid . ".200." . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, 200, 200);
        }
        $picture = file_create_url($newpicture);
      }
      else if ($size == 'pnode')  // 150x150
      {
        $info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picture-' . $account->uid . ".150." . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, 150, 150);
        }
        $picture = file_create_url($newpicture);
      }
      else if ($size == 'taxonomy')  // 80x80
      {
        $info = image_get_info($account->picture);
        $newpicture = dirname($account->picture) . '/picture-' . $account->uid . ".95." . $info['extension'];
        if (!file_exists($newpicture) || (filectime($newpicture) < filectime($account->picture))) {
          image_scale($account->picture, $newpicture, 95, 95);
        }
        $picture = file_create_url($newpicture);
      }
      else
      {
        $picture = file_create_url($account->picture);
      }
    }
    else if (variable_get('user_picture_default', '')) {
      $picture = variable_get('user_picture_default', '');
    }

    if (isset($picture)) {
      $alt = t($account->name.'\'s picture', array('%user' => $account->name ? $account->name : variable_get('anonymous', 'Anonymous')));
      $picture = theme('image', $picture, $alt, $alt, '', false);
      if (!empty($account->uid) && user_access('access user profiles')) {
        $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE);
      }

      print_r("<div class=\"picture\">$picture</div>");
    }
  }

lias’s picture

Is this it?

$newpicture = dirname($account->picture) . '/picture-' . $account->uid . ".150." . $info['extension'];

What does the dirname($account->picture) part do? I gather that this '/picture-' . $account->uid . ".150." . $info['extension']; is what builds the picture names?

The reason I ask is that I would like all new picture versions to be created in the pictures directory only. What happened is that I'm also using avatar selection module and when a avatar is selected, rather than uploading the new picture version (comment size etc) to the files/pictures directory they're saved to the directory of files/avatar_selection which screws up the display.

Thanks.

amnion’s picture

http://www.lullabot.com/articles/imagecache_example_user_profile_pictures

Ever since I used this tutorial I haven't had a problem with my pictures being resized.

totocol’s picture

Would not be easier just using CSS max-height and max-width?

chadchandler’s picture

No. You should never resize images with CSS or HTML. Use the image-cache module along with image-profile-picture-cache module, available as a link on the image cache homepage.