Solved

Resize Proportionately

Posted on 2012-03-29
2
314 Views
Last Modified: 2012-05-24
Hello,

I have the below and I would like to make the resize fit the max of 850w or 500h.

Can you please let me know what the code is that will do this.

Thanks!

if(move_uploaded_file($tempFile, $targetFile))
			{
				require_once("functions.php");
				resizeImage(850, 500, $targetFile, $targetFile);
				

Open in new window

0
Comment
Question by:movieprodw
2 Comments
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 37787143
I have something similar here.  It is driven only by the width, but with a few lines of additional code, you could also test the height.  To see how this works, look at lines 54-62 where we test the width.

HTH, ~Ray
<?php // RAY_image_resize.php
error_reporting(E_ALL);

// RESIZE A PNG IMAGE TO FIT A PREDEFINED SIZE.  USES THE GD LIBRARY.
// MAN PAGES: http://php.net/manual/en/ref.image.php

// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{
    // IS GD INSTALLED AT ALL?  http://php.net/manual/en/function.gd-info.php
    if (!function_exists("gd_info"))
    {
        if ($display) echo "<br/>GD NOT INSTALLED\n";
        return FALSE;
    }

    // IF GD IS INSTALLED GET DETAILS
    $gd = gd_info();

    // IF DISPLAY IS REQUESTED, PRINT DETAILS
    if ($display)
    {
        echo "<br/>GD DETAILS:\n";
        foreach ($gd as $key => $value)
        {
            if ($value === TRUE)  $value = 'YES';
            if ($value === FALSE) $value = 'NO';
            echo "<br/>$key = $value \n";
        }
    }

    // RETURN THE VERSION NUMBER
    $gd_version = preg_replace('/[^0-9\.]/', '', $gd["GD Version"]);
    return $gd_version;
}


// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=300)
{
    // IS GD HERE?
    $gdv = get_gd_info();
    if (!$gdv) return FALSE;

    // GET AN IMAGE RESOURCE http://php.net/manual/en/function.imagecreatefromjpeg.php
    $source = imagecreatefrompng("$image");

    // GET THE X AND Y DIMENSIONS http://php.net/manual/en/function.imagesx.php
    $imageX = imagesx($source);
    $imageY = imagesy($source);

    // IF NO RESIZING IS NEEDED
    if ($imageX <= $width)
    {
        return FALSE;
    }

    // THE WIDTH IS TOO GREAT - MUST RESIZE
    $tnailX = $width;
    $tnailY = (int) (($tnailX * $imageY) / $imageX );

    // WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
    if ($gdv >= 2)
    {
        // IF GD IS AT LEVEL 2 OR ABOVE USE http://php.net/manual/en/function.imagecreatetruecolor.php
        $target = imagecreatetruecolor($tnailX, $tnailY);
        imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
    }
    else
    {
        // IF GD IS AT A LOWER REVISION LEVEL
        $target = imagecreate($tnailX, $tnailY);
        imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
    }
    // RETURN THE IMAGE RESOURCE
    return $target;
}



// SAMPLE CALLING SEQUENCE - SET THE FILE PATH URLS
$old = 'RAY_orig_600x374.png';
$new = 'RAY_temp_300x187.png';

// RESIZE THE FILE TO FIT DESIRED WIDTH, IF NECESSARY
if ($image_resource = create_right_size_image($old))
{
    // WRITE (OVERWRITE) THE IMAGE IN THE NEW FILE http://php.net/manual/en/function.imagepng.php
    imagepng($image_resource, $new);

    // FREE THE MEMORY USED FOR THE IMAGE
    imagedestroy($image_resource);

    // SHOW A LINK TO THE NEW IMAGE
    echo '<a target="_blank" href="' . $new . '">SEE NEW ' . $new . '</a>' . PHP_EOL;
}

// IF IMAGE DID NOT NEED TO BE RESIZED - WAS EQUAL OR SMALLER THAN DESIRED WIDTH
echo 'ORIGINAL: <a target="_blank" href="' . $old . '">SEE OLD ' . $old . '</a>' . PHP_EOL;

Open in new window

0
 
LVL 10

Expert Comment

by:Derokorian
ID: 37787232
This function will resize your image to fit within the maximum width / height provided OR will resize it to the exact width / height provided depending on the last option (defaults to maximum dimensions).

<?php

/**
 * This function resizes a given image into the target file with the given width and height
 *
 * @author Ryan "Derokorian" Pallas
 *
 * @example usage
 *      $src = "C:\www\images\uploads\image.jpg";
 *      $targ = "C:\www\images\uploads\thumbs\image.jpg";
 *      if( imageResize($src,$targ,100,75) ) echo "Successfully resized thumbnail";
 * 
 * @param string $src Source input file to be resized
 * @param string $target Target output after resizing
 * @param int $newWidth Target width
 * @param int $newHeight Target height
 * @param bool $abs Whether newwidth/newheight are final or maximum measurements (Default: FALSE)
 *
 * @return bool
 */
function imageResize($src,$target,$newWidth,$newHeight,$abs=FALSE)
    {
    /**
     * @var array source image info
     */
    $imgInfo = getimagesize($src);
    
    /**
     * return false if not an image
     */
    if($imgInfo == FALSE) return FALSE;
    
    /**
     * @var int width
     * @var int height
     * @var constant img type
     */
    list($origWidth,$origHeight,$imgtype) = $imgInfo;
    
    /**
     * absolute dimensions or max dimensions
     */
    if( !$abs )
        {
        /**
         * determine new width & height based on aspect ratio
         */
        $ratio = (($origWidth / $origHeight) > ($newWidth / $newHeight)) ? $newWidth / $origWidth : $newHeight / $origHeight; 
        $newWidth = (int) ($origWidth * $ratio); // set width with ratio
        $newHeight = (int) ($origHeight * $ratio); // set height with ratio
        
        /**
         * if original dimensions smaller than new, do not resize
         */
        if( $origHeight <= $newHeight && $origWidth <= $newWidth)
            {
            $newHeight = $origHeight;
            $newWidth = $origWidth;
        }
        
        /**
         * @var int image offset for resampling
         */
        $xOffset = 0;
        $yOffset = 0;
    } else
        {
        /**
         * set original sampling area based on exact new dimensions
         */
        $ratio = (($origWidth / $origHeight) < ($newWidth / $newHeight)) ? $newWidth / $origWidth : $newHeight / $origHeight; 
        $finalHeight = (int) floor($newHeight / $ratio);
        $finalWidth = (int) floor($newWidth / $ratio);
        
        /**
         * @var int offset to center resampling area on original source
         */
        $yOffset = ($finalHeight == $origHeight) ? 0 : floor( ($origHeight-$finalHeight)/2 );
        $xOffset = ($finalWidth == $origWidth) ?  0 : floor( ($origWidth-$finalWidth)/2 );
        
        /**
         * @var int resampling area of original source
         */
        $origHeight = $finalHeight;
        $origWidth = $finalWidth;
    }
    
    /**
     * determine file type for correct functions
     */
    switch($imgtype)
        { 
        case IMAGETYPE_JPEG: 
            $create = "imagecreatefromjpeg"; 
            $move = "imagejpeg"; 
            break; 
        case IMAGETYPE_GIF: 
            $create = "imagecreatefromgif"; 
            $move = "imagegif"; 
            break; 
        case IMAGETYPE_PNG: 
            $create = "imagecreatefrompng"; 
            $move = "imagepng"; 
            break; 
        case IMAGETYPE_WBMP: 
            $create = "imagecreatefromwbmp"; 
            $move = "imagewbmp"; 
            break; 
        default: 
            return FALSE; 
    }
    
    /**
     * @var image create image from source
     */
    $base = $create($src);
    
    /**
     * @var image create image to new size
     */
    $temp = imagecreatetruecolor($newWidth,$newHeight);
    
    /**
     * copy resampled original and resize to new image
     */
    imagecopyresampled($temp,$base,0,0,$xOffset,$yOffset,$newWidth,$newHeight,$origWidth,$origHeight);
    
    /**
     * move new image to destination
     * return true on success, false on failure
     */
    if ( $move($temp,$target) )
        {
        return TRUE;
    } else
        {
        return FALSE;
    }
}

Open in new window

0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

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…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
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.

773 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