Page 1 of 1

Upload avatar script?

Posted: Sat Jul 30, 2005 11:20 am
by Todd_Z
I'm trying to modify the following script to
a.) Change the img size to a max of 140*140
b.) Convert all formats of image to jpg

Code: Select all

$fn = str_replace( ' ', '', $_FILES['a']['name'] );
  $le = strlen( $fn );
  $ext = substr( $fn, $le-3, $le );
  if ($ext == 'png' || $ext == 'gif' || $ext == 'jpg') {
    $upd = "/home/****/public_html/imgs/users/";
    $upf = "$upd{$_SESSION['uid']}.$ext";
    move_uploaded_file( $_FILES['a']['tmp_name'], $upf ) or $errors[] = "Failed to upload avatar";
  }

Posted: Sat Jul 30, 2005 11:22 am
by shiznatix
you are going to have to go by if $ext is png then imagecreatefrompng or whatever that function is called then create a jpg with the image created and then do the same thing with the rest

Posted: Sat Jul 30, 2005 12:32 pm
by josh
For users without image editing softwear you could use imagecopyresampled() to automatically resize their avatars for them if they go over the limit.

Using gd you could do a switch of the image type, using imagecreatfrom****() for the right kind of image, you could resize the image then call imagejpeg() to output the jpeg image.

If you want to just deny images over your limit, getimagesize()

Posted: Sat Jul 30, 2005 1:18 pm
by Todd_Z
Thanks folks

Code: Select all

$fn = str_replace( ' ', '', $_FILES['a']['name'] );
$le = strlen( $fn );
$ext = substr( $fn, $le-3, $le );
if ($ext == 'png' || $ext == 'gif' || $ext == 'jpg') {
  $upd = "/home/****/public_html/imgs/users/";
  $upf = "$upd{$_SESSION['id']}.$ext";
  if ( $ext == 'png' ) $img = imagecreatefrompng( $_FILES['a']['tmp_name'] );
  if ( $ext == 'gif' ) $img = imagecreatefromgif( $_FILES['a']['tmp_name'] );
  if ( $ext == 'jpg' ) $img = imagecreatefromjpeg( $_FILES['a']['tmp_name'] );
  $x = imagesx( $img );
  $y = imagesy( $img );
  if ( $x > 140 ) {
    $x = 140;
    $y = round(140/$x * $y);
  }
  if ( $y > 140 ) {
    $y = 140;
    $x = round(140/$y * $x);
  }
  $nimg = imagecreate( $x, $y );
  imagecopyresized( $nimg, $img, 0, 0, 0, 0, $x, $y, imagesx($img), imagesy($img) );
  imagejpeg( $nimg, "/home/*****/public_html/imgs/users/{$_SESSION['uid']}.jpg", 100 );
}

Posted: Sat Jul 30, 2005 2:37 pm
by josh
Todd_Z wrote:Thanks folks

Code: Select all

imagecopyresized( $nimg, $img, 0, 0, 0, 0, $x, $y, imagesx($img), imagesy($img) );
php.net wrote:Better quality could be obtained using imagecopyresampled().
Might consider taking a look at imagecreatetruecolor(), rather then imagecreate()

Also for obtaining the correct function to use based on the extension something like this works better IMO, due to possible file extension of 'jpg' or 'jpeg' for a jpeg image, a switch is nice in the way it handles multiple cases:

Code: Select all

switch ($ext) {
   case 'jpg':
   case 'jpeg':
        // Jpg code
   break;
   case 'gif':
        // gif code
   break;
}