What's the easiest way to resize $user->picture?

ajwwong - April 17, 2006 - 17:54

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

Well, I'm still working on this... thought I'd post my latest...

ajwwong - April 23, 2006 - 00:46

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

Like the idea...

bradlis7 - April 23, 2006 - 00:59

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

so,I have looked at the image.module briefly

ajwwong - April 24, 2006 - 17:34

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:

<?php
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>')));
    }
  }
}
?>

It makes sense that

bradlis7 - April 24, 2006 - 18:36

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,

<?php
 
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.

<?php
 
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:

<?php
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

holy kamole!

ajwwong - April 24, 2006 - 19:30

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

Well... not working, yet...

ajwwong - April 26, 2006 - 20:25

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

So, an easy work around

bradlis7 - April 26, 2006 - 21:36

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

<?php
$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

Bingo!!!

ajwwong - April 26, 2006 - 22:49

That did it bradlis!!

Perfectomundo....

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

Blessings to you,

Albert
www.ithou.org

OK, so... I did it!! --- with help from bradlis7 & others

ajwwong - April 27, 2006 - 09:47

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:

<?php
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:

<?php
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:

<?php
 
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

Patch

hba - May 2, 2006 - 19:39

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

how bout having more images for the user profile?

bombaclot - May 9, 2006 - 05:21

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

Full Module

bradlis7 - May 9, 2006 - 17:44

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

Path gets printed

Ayza - July 24, 2006 - 19:00

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

ditto here.. can anybody help?

netceo - July 27, 2006 - 04:14

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

Same Results

txcrew - August 10, 2006 - 17:17

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

Hi everyone, and sorry I'm away for so long...

ajwwong - August 12, 2006 - 16:33

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

the giffy thang

Ayza - August 14, 2006 - 10:14

Thanx Albert,

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

For anyone else reading

UnderDesign - January 16, 2007 - 20:22

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

How about a cron job?

EnekoAlonso - August 15, 2006 - 22:48

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! :)

Sounds like a good idea

Ayza - August 16, 2006 - 07:47

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

:-)

Ayza

Another way, without modifying Drupal's code.

EnekoAlonso - August 17, 2006 - 04:56

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!

Wow!

ajwwong - August 18, 2006 - 08:35

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

Thanks for this wonderful

txcrew - August 20, 2006 - 05:07

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

usage of this code

EnekoAlonso - August 28, 2006 - 18:10

as ajwwong suggested:

<?php
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.

Excellent code... !!!

ajwwong - August 30, 2006 - 02:48

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]

<?php
 
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

User picture thumbnails in bluemarine

hba - September 6, 2006 - 07:46

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.

Current user profile picture

Steel Rat - September 23, 2006 - 22:28

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

6.x?

bobzillaforever - April 3, 2008 - 16:08

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.

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

Anyone else trying to get this to work?

hi

gurukripa - May 18, 2007 - 10:21

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

Thanks. (bookmarking)

genemcc - October 6, 2006 - 10:51

Thanks. (bookmarking)

Hi there,

patchak - November 1, 2006 - 20:24

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

I just used this code to

j0k3z - January 23, 2007 - 03:10

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.

has anybody gotten this code

j0k3z - January 24, 2007 - 13:04

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

not working in 5.x

BradM - March 25, 2007 - 05:18

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

Me too

stephencarr - May 13, 2007 - 15:43

This working in 5.1 would be really nice.

I tried EnekoAlonso's code

r.smith - June 27, 2007 - 22:51

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

the code works but uses too much memory

gurukripa - October 9, 2007 - 17:07

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

Great! But....<em></em>'s Picture??

sameersegal - October 23, 2007 - 19:15

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

Hey, I have just tried the

enzipher - December 28, 2007 - 04:47

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

<?php
   
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!

Try This

dyutiman - June 21, 2007 - 09:23

Try something like this

<?php
 
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.

dyutiman, what exactly did you change?

lsabug - February 11, 2008 - 00:18

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

Resize and Compress during user upload (IMCE / FCKeditor)

Quint - February 26, 2007 - 18:39

(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

Resize Solved

Quint - February 26, 2007 - 18:56

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

resize $user->picture?

coupet - April 18, 2007 - 23:07

Does it work in 5.x ?

----
Darly

yeah

Quint - April 22, 2007 - 21:29

yeah, I'm in 5.1

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

Do you made any

SimonVlc - May 2, 2007 - 00:25

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

Kind regards, Simon.

Doesn´t matter, I solve

SimonVlc - May 2, 2007 - 23:50

Doesn´t matter, I solve it.

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

<?php
global $user;
?>

Is this convenient? Is there any other form?

Thanks in advance, Simon.

pls can u put the full procedure for 5.1

gurukripa - May 18, 2007 - 09:42

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

pls help quint :)

gurukripa - October 9, 2007 - 13:13

dear quint

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

thanks a lot in advance.

Did you figure it out?

Quint - October 17, 2007 - 22:55

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

great job

alynner - May 28, 2007 - 22:41

thanks!
(just bookmarking)

subscribe

yngens - July 26, 2007 - 05:59

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.

bokmarkin

droople - October 26, 2007 - 21:09

subscribing

subscribe - thx

scottrigby - October 29, 2007 - 15:07

function doesn't work for default pictures?

sylvie_n - November 9, 2007 - 15:53

This function isn't working for my default pictures?

I am also getting <em></em>'s Picture??

sylvie_n - November 10, 2007 - 10:21

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

<?php
 
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)

I'm also looking for the

Prodigy - November 15, 2007 - 20:26

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.

Same < em > code for user picture

lsabug - December 1, 2007 - 18:39

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.

same problem, doesn't affect default pics

lsabug - February 11, 2008 - 01:01

?

bookmark

thepaul - December 4, 2007 - 04:07

bookmark

Use CSS to rezise images

72dpi - December 4, 2007 - 07:06

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...

Mainly because that's only

Steel Rat - December 14, 2007 - 20:01

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

Try out the ImageCache

v1nce - December 31, 2007 - 02:49

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.

Hey guys, code works great.

sylvie_n - February 1, 2008 - 14:27

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:

<?php
 
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>");
    }
  }
?>

where is the filepath of the new images set in code?

lsabug - February 11, 2008 - 04:55

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.

Here is a good article that helped me

amnion - May 28, 2008 - 17:24

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.

Using CSS

totocol - February 16, 2009 - 22:50

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

No. You should never resize

Prodigy - February 17, 2009 - 02:42

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.

 
 

Drupal is a registered trademark of Dries Buytaert.