Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Resizing image with same aspect ratio

Status
Not open for further replies.

gandalf458

IS-IT--Management
Jul 23, 2015
24
0
0
IT
I have a script that uploads and if necessary resizes an image. It works fine except that if the uploaded image is not the same aspect ratio as the source image it gets distorted. Can anyone help me work out what I need to add to change the aspect ratio please?

PHP:
$image = 'img'.date('U').'.'.$extn;
$destfile = '../video-img/'.$image;
$tempfile = '../temp/'.$image;
$tempname = $_FILES['image']['tmp_name'];
$size = getimagesize($tempname);
$width  = 800;
$height = 450;
if ( ($size[0] < $width) || ($size[1] < $height) )
  echo '<p class="error">Image ', $filename, ' is too small but will be resized and uploaded.</p>', "\n";

// if image is the right size, just save it
if ( ($size[0] === $width) || ($size[1] === $height) ) {
  if ( !(is_uploaded_file($tempname) && move_uploaded_file($tempname, $destfile)) )
    echo '<p class="error">Image ', $filename, ' could not be uploaded.</p>', "\n";
}
// if image is not the right size, save it to a temporary are and then resize it
else {
  if ( !(is_uploaded_file($tempname) && move_uploaded_file($tempname, $tempfile)) )
    echo '<p class="error">Image ', $filename, ' could not be uploaded.</p>', "\n";
  $resized = imagecreatetruecolor($width, $height);

  if ( $extn == 'jpg' or $extn == 'jpeg' ) {
    $srcfile = imagecreatefromjpeg($tempfile);
    imagecopyresampled($resized, $srcfile, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
    imagejpeg($resized, $destfile, 80);
  }
  elseif ( $extn == 'png' ) {
    $srcfile = imagecreatefrompng($tempfile);
    imagecopyresampled($resized, $srcfile, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
    imagepng($resized, $destfile, 6);
  }
  imagedestroy($resized);
  imagedestroy($srcfile);
  unlink($tempfile);
}

I'm not a number, I'm a free man
 
The predefined $width and $height is causing the problem. You need to calculate that instead of defining 800 and 450.

Assuming that you want the image to be 800 pixels wide, calculate what percentage of the original $size[0] would equal 800 pixels ($width). Then apply that same percentage to $size[1] to determine the proper $height.

Don't forget to round the $height to an integer.
 
Thanks spamjim.

I'm not a number, I'm a free man
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top