Solved

resizeing PHP image

Posted on 2016-11-13
2
22 Views
Last Modified: 2016-11-28
I have this simple code I got from online that resizes my images to a certain shape

I am specifying max width/height.
Right, now I am always getting a square, and it's cutting off my image.
How can I adjust the code to use it as a max height/width, and constraint the image keeping the size it is now, and figure out the ration that the other side should be?
unction resize($width, $height){
  /* Get original image x y*/
  list($w, $h) = getimagesize($_FILES['image']['tmp_name']);
  /* calculate new image size with ratio */
  $ratio = max($width/$w, $height/$h);
  $h = ceil($height / $ratio);
  $x = ($w - $width / $ratio) / 2;
  $w = ceil($width / $ratio);


if ($w >= $width && $h >= $height) {
    // get scales.
    $x_scale = ($w / $width);
    $y_scale = ($h / $height);

    // create new image.
    $out = imagecreatetruecolor($width, $height);

    $new_w = $width;
    $new_h = $height;
    $src_x = 0;
    $src_y = 0;

    // compare scales to ensure we crop whichever is smaller: top/bottom or
    // left/right.
    if ($x_scale > $y_scale) {
        $new_w = $w / $y_scale;

        // see description of $src_y, below.
        $src_x = (($new_w - $width) / 2) * $y_scale;
    } else {
        $new_h = $h / $x_scale;

        // a bit tricky. crop is done by specifying coordinates to copy from in
        // source image. so calculate how much to remove from new image and
        // then scale that up to original. result is out by ~1px but good enough.
        $src_y = (($new_h - $height) / 2) * $x_scale;
    }

	
  /* new file name */
  $path = '../images/upload/'.$w.'x'.$h.'_'.$_FILES['image']['name'];
  /* read binary data from image file */
  $imgString = file_get_contents($_FILES['image']['tmp_name']);
  /* create image from string */
  $image = imagecreatefromstring($imgString);
  $tmp = imagecreatetruecolor($width, $height);
      imagecopyresampled($tmp, $image, 0, 0, $src_x, $src_y, $new_w, $new_h, $w, $h);

 /*imagecopyresampled($tmp, $image,
    0, 0,
    $x, 0,
    $width, $height,
    $w, $h);*/
  /* Save image */
  switch ($_FILES['image']['type']) {
    case 'image/jpeg':
      imagejpeg($tmp, $path, 100);
      break;
    case 'image/png':
      imagepng($tmp, $path, 0);
      break;
    case 'image/gif':
      imagegif($tmp, $path);
      break;
    default:
      exit;
      break;
  }
  return $path;
  /* cleanup memory */
  imagedestroy($image);
  imagedestroy($tmp);
}
}

Open in new window

0
Comment
Question by:rivkamak
2 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 41885938
Here is my teaching example showing the essential moving parts.  In these examples, the file will already be on the server (file uploading is a separate issue, for security reasons).
https://iconoun.com/demo/image_resize_and_crop.php
<?php // demo/image_resize_and_crop.php
/**
 * Resize an image proportionally
 * Crop to specified size
 *
 * https://www.experts-exchange.com/questions/28982826/resizeing-PHP-image.html
 */
error_reporting(E_ALL);

function resize_and_crop($original_image_url, $thumb_image_url, $thumb_w, $thumb_h, $quality=75)
{
    // ACQUIRE THE ORIGINAL IMAGE: http://php.net/manual/en/function.imagecreatefromjpeg.php
    $original = imagecreatefromjpeg($original_image_url);
    if (!$original) return FALSE;

    // GET ORIGINAL IMAGE DIMENSIONS
    list($original_w, $original_h) = getimagesize($original_image_url);

    // RESIZE IMAGE AND PRESERVE PROPORTIONS
    $thumb_w_resize = $thumb_w;
    $thumb_h_resize = $thumb_h;
    if ($original_w > $original_h)
    {
        $thumb_h_ratio  = $thumb_h / $original_h;
        $thumb_w_resize = (int)round($original_w * $thumb_h_ratio);
    }
    else
    {
        $thumb_w_ratio  = $thumb_w / $original_w;
        $thumb_h_resize = (int)round($original_h * $thumb_w_ratio);
    }
    if ($thumb_w_resize < $thumb_w)
    {
        $thumb_h_ratio  = $thumb_w / $thumb_w_resize;
        $thumb_h_resize = (int)round($thumb_h * $thumb_h_ratio);
        $thumb_w_resize = $thumb_w;
    }

    // CREATE THE PROPORTIONAL IMAGE RESOURCE
    $thumb = imagecreatetruecolor($thumb_w_resize, $thumb_h_resize);
    if (!imagecopyresampled($thumb, $original, 0,0,0,0, $thumb_w_resize, $thumb_h_resize, $original_w, $original_h)) return FALSE;

    // ACTIVATE THIS TO STORE THE INTERMEDIATE IMAGE
    // imagejpeg($thumb, 'thumbs/temp_' . $thumb_w_resize . 'x' . $thumb_h_resize . '.jpg', 100);

    // CREATE THE CENTERED CROPPED IMAGE TO THE SPECIFIED DIMENSIONS
    $final = imagecreatetruecolor($thumb_w, $thumb_h);

    $thumb_w_offset = 0;
    $thumb_h_offset = 0;
    if ($thumb_w < $thumb_w_resize)
    {
        $thumb_w_offset = (int)round(($thumb_w_resize - $thumb_w) / 2);
    }
    else
    {
        $thumb_h_offset = (int)round(($thumb_h_resize - $thumb_h) / 2);
    }

    if (!imagecopy($final, $thumb, 0,0, $thumb_w_offset, $thumb_h_offset, $thumb_w_resize, $thumb_h_resize)) return FALSE;

    // STORE THE FINAL IMAGE - WILL OVERWRITE $thumb_image_url
    if (!imagejpeg($final, $thumb_image_url, $quality)) return FALSE;
    return TRUE;
}


// USE CASE
echo '<a target="_blank" href="images/image_600x374.jpg">Original 600x374</a><br/>';

resize_and_crop('images/image_600x374.jpg', 'thumbs/temp_100x100.jpg', 100, 100);
echo '<a target="_blank" href="thumbs/temp_100x100.jpg">100x100</a><br/>';

resize_and_crop('images/image_600x374.jpg', 'thumbs/temp_200x100.jpg', 200, 100);
echo '<a target="_blank" href="thumbs/temp_200x100.jpg">200x100</a><br/>';

resize_and_crop('images/image_600x374.jpg', 'thumbs/temp_200x300.jpg', 200, 300);
echo '<a target="_blank" href="thumbs/temp_200x300.jpg">200x300</a><br/>';

Open in new window

0
 
LVL 26

Expert Comment

by:skullnobrains
ID: 41886118
function get_thumb_size($imgH,$imgV,$maxH,$maxV){

  // resize according to width ( Horizontal ), preserve ratio
  $maxH < $imgH
  and $retH=$maxH
  and $retV=round($imgV * $retH / $imgH);
  
  // if the image is not to high, return the new dimensions
  if($retv <= $maxV)return array($retH,$retV);
  
  // otherwise return dimensions resized according to height
  return array(round($imgH * $maxV / $imgV) , $maxV);
}

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now