2

I have a quick question that I'm not quite sure to set up. I've seen examples elsewhere but nothing specifically like my situation. I would like to resize images using PHP so they're readable and not just wonkily stretched like if you use HTML. If they're not 250 pixels wide, or 160 pixels tall, how can I resize the picture so it's proportionate but fits within that space?

Thanks!

Sara
  • 133
  • 5
  • 11
  • 2
    Out of interest, have you done any research into this already? – Jonnix Sep 12 '11 at 20:07
  • There's also a php class named "Watimage" really useful (I use it on almost all my projects) that will help you resize images very easily: http://bit.ly/wO9FMq – elboletaire Aug 27 '12 at 11:42

6 Answers6

6

PHP does not manipulate images directly. You will need to use an image manipulation library such as gd or ImageMagick to accomplish this goal.

In ImageMagick, image resizing is accomplished like this:

$thumb = new Imagick('myimage.gif');

$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');

With GD, you can do it like this:

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>
George Cummins
  • 28,485
  • 8
  • 71
  • 90
4

Ok, so below is an Image object that I use in my store. It maintains scale - requires GD

<?php
class Store_Model_Image extends My_Model_Abstract 
{
    const PATH  = STORE_MODEL_IMAGE_PATH;
    const URL   = "/store-assets/product-images/";

    public function get_image_url($width, $height)
    {
        $old_file = self::PATH . $this->get_filename();
        $basename = pathinfo($old_file, PATHINFO_FILENAME);

        $new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);
        if(file_exists(self::PATH . $new_name))
        {
            return self::URL . $new_name;
        }
        else
        {
            list($width_orig, $height_orig, $image_type) = @getimagesize($old_file);
            $img = FALSE;

            // Get the image and create a thumbnail     
            switch($image_type)
            {
                case 1:
                    $img = @imagecreatefromgif($old_file);
                    break;
                case 2:
                    $img = @imagecreatefromjpeg($old_file);
                    break;
                case 3: 
                    $img = @imagecreatefrompng($old_file);
                    break;
            }

            if(!$img)
            {
                throw new Zend_Exception("ERROR: Could not create image handle from path.");
            }

            // Build the thumbnail
            if($width_orig > $height_orig)
            {
                $width_ratio = $width / $width_orig;
                $new_width   = $width;
                $new_height  = $height_orig * $width_ratio;
            }
            else
            {
                $height_ratio = $height / $height_orig;
                $new_width    = $width_orig * $height_ratio;
                $new_height   = $height;
            }

            $new_img = @imagecreatetruecolor($new_width, $new_height);

            // Fill the image black
            if(!@imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))
            {           
                throw new Zend_Exception("ERROR: Could not fill new image");
            }

            if(!@imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))
            {
                throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");
            }

            // Use a output buffering to load the image into a variable
            ob_start();
            imagejpeg($new_img, NULL, 100);
            $image_contents = ob_get_contents();
            ob_end_clean();

            // lastly (for the example) we are writing the string to a file
            $fh = fopen(self::PATH . $new_name, "a+");
            fwrite($fh, $image_contents);
            fclose($fh);

            return self::URL . $new_name;
        }
    }
}

I resize the image at request time, so the first time the page loads an image will be resized to the required size for the template. (this means I don't have to crash a shared host trying to regenerate image thumbnails everytime my design changes)

So in the template you pass your image object, and when you need a image thumb,

<img src="<?php echo $image->get_image_url(100, 100); ?>" />

you now have a 100x100 thumb, which is saved to the Server for reuse at a later date

Francis Yaconiello
  • 10,829
  • 2
  • 35
  • 54
1

gd and imagemagick are two tools that may work for you

Deep Kapadia
  • 1,468
  • 8
  • 21
0

There a simple to use, open source library called PHP Image Magician that will can help you out.

Example of basis usage:

$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');
Jarrod
  • 9,349
  • 5
  • 58
  • 73
0

Here is something I used to use

class cropImage{

    var $imgSrc,$myImage,$cropHeight,$cropWidth,$x,$y,$thumb;  

    function setImage($image,$moduleWidth,$moduleHeight,$cropPercent = "1") {

        //Your Image
        $this->imgSrc = $image; 

        //getting the image dimensions
        list($width, $height) = getimagesize($this->imgSrc); 

        //create image from the jpeg
        $this->myImage = imagecreatefromjpeg($this->imgSrc) or die("Error: Cannot find image!"); 

         if($width > $height) $biggestSide = $width; //find biggest length
         else $biggestSide = $height; 

        //The crop size will be half that of the largest side 
        //$cropPercent = 1.55; // This will zoom in to 50% zoom (crop)

        if(!$cropPercent) {
            $cropPercent = 1.50;
        }

        $this->cropWidth   = $moduleWidth*$cropPercent; 
        $this->cropHeight  = $moduleHeight*$cropPercent; 
        //$this->cropWidth   = $biggestSide*$cropPercent; 
        //$this->cropHeight  = $biggestSide*$cropPercent; 


        //getting the top left coordinate
        $this->x = ($width-$this->cropWidth)/2;
        $this->y = ($height-$this->cropHeight)/2;

    }  

    function createThumb($moduleWidth,$moduleHeight){

        $thumbSize = 495; // will create a 250 x 250 thumb
        $this->thumb = imagecreatetruecolor($moduleWidth, $moduleHeight); 
        //$this->thumb = imagecreatetruecolor($thumbSize, $thumbSize); 

        imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $moduleWidth, $moduleHeight, $this->cropWidth, $this->cropHeight); 
        //imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $thumbSize, $thumbSize, $this->cropWidth, $this->cropHeight); 
    }  

    function renderImage(){
        header('Content-type: image/jpeg');
        imagejpeg($this->thumb);
        imagedestroy($this->thumb); 
    }  

}  

Call it by using

$image = new cropImage;
$image->setImage($imagepath,$moduleWidth,$moduleHeight,$scaleRelation);
$image->createThumb($moduleWidth,$moduleHeight);
$image->renderImage();
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
0

Use GD or ImageMagick. Here you may find a real production example of code (used by MediaWiki) that supports consoled ImageMagick interface (transformImageMagick method), ImageMagick extension interface (transformImageMagickExt method) and GD (transformGd method).

Victor Vasiliev
  • 462
  • 2
  • 12