Solved

resizeing PHP image

Posted on 2016-11-13
2
42 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
object oriented programming comparison 5 57
Hacked File Timestamps 4 51
PHP - AJAX and MySQL it works only if the value is a number 12 38
PHP: concatenate query 13 45
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

863 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

19 Experts available now in Live!

Get 1:1 Help Now