Resizing the image in php for viewing purposes only
Asked Answered
P

16

9

Okay, the reason I posted this is because I wasn't sure what to search for. I'll try to explain it as clearly as I can.

Say, I have an image sized 800x600. The box I've allotted for the image is 150x150 and has to be satisfied at all times. I can only allow an image to be shown at a maximum size of 150px for both height and width. So, technically, the image has to be scaled down to 200x150.

Now, the question:

Is there a way I can crop the height so it only shows 150x150? This is for viewing purposes only. I don't need to save the image as a new file.

A good example is your profile page in Twitter. It shows your profile image cropped but when you click on it, you still get the image you originally uploaded.

[EDIT] Here's what I'm trying to achieve. Get the smaller side in terms of pixels, resize it to 150px then hide the overflowing part of the other side. Again, no saving involved. Just for people's viewing pleasure.

What I'm trying to accomplish

Pissarro answered 6/3, 2012 at 10:14 Comment(3)
Try TimThumb. It can do cropping, zooming and resizing of images on the fly.Hobbes
Try to avoid on-the-fly image processing, it will create a lot of load on your servers. We use .htaccess rewrite rules so that we can save the file to disk and serve it directly after the initial view. If I had time right now I would post you an answer on how we do this.Adherence
@Hobbes TimThumb has been deprecated. The author wrote this post explaining why it should no longer be used: binarymoon.co.uk/2014/09/timthumb-end-lifeEldin
C
36

I use a simple PHP class which has several options for resizing. You can easily store the thumbnails via this class. As @jeroen said, you only have to do it once and they can be cached. It just requires PHP5 and GD library. Here is usage example:

// *** Include the class
include("resize-class.php");

// *** 1) Initialise / load image
$resizeObj = new resize('sample.jpg');

// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(150, 150, 'crop');

// *** 3) Save image ('image-name', 'quality [int]')
$resizeObj -> saveImage('sample-resized.jpg', 100);

And this is that class:

<?php
        Class resize
        {
            // *** Class variables
            private $image;
            private $width;
            private $height;
            private $imageResized;

            function __construct($fileName)
            {
                // *** Open up the file
                $this->image = $this->openImage($fileName);

                // *** Get width and height
                $this->width  = imagesx($this->image);
                $this->height = imagesy($this->image);
            }

            ## --------------------------------------------------------

            private function openImage($file)
            {
                // *** Get extension
                $extension = strtolower(strrchr($file, '.'));

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        $img = @imagecreatefromjpeg($file);
                        break;
                    case '.gif':
                        $img = @imagecreatefromgif($file);
                        break;
                    case '.png':
                        $img = @imagecreatefrompng($file);
                        break;
                    default:
                        $img = false;
                        break;
                }
                return $img;
            }

            ## --------------------------------------------------------

            public function resizeImage($newWidth, $newHeight, $option="auto")
            {
                // *** Get optimal width and height - based on $option
                $optionArray = $this->getDimensions($newWidth, $newHeight, $option);

                $optimalWidth  = $optionArray['optimalWidth'];
                $optimalHeight = $optionArray['optimalHeight'];


                // *** Resample - create image canvas of x, y size
                $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
                imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);


                // *** if option is 'crop', then crop too
                if ($option == 'crop') {
                    $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
                }
            }

            ## --------------------------------------------------------

            private function getDimensions($newWidth, $newHeight, $option)
            {

               switch ($option)
                {
                    case 'exact':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                        break;
                    case 'portrait':
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                        break;
                    case 'landscape':
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                        break;
                    case 'auto':
                        $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                    case 'crop':
                        $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
                        $optimalWidth = $optionArray['optimalWidth'];
                        $optimalHeight = $optionArray['optimalHeight'];
                        break;
                }
                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getSizeByFixedHeight($newHeight)
            {
                $ratio = $this->width / $this->height;
                $newWidth = $newHeight * $ratio;
                return $newWidth;
            }

            private function getSizeByFixedWidth($newWidth)
            {
                $ratio = $this->height / $this->width;
                $newHeight = $newWidth * $ratio;
                return $newHeight;
            }

            private function getSizeByAuto($newWidth, $newHeight)
            {
                if ($this->height < $this->width)
                // *** Image to be resized is wider (landscape)
                {
                    $optimalWidth = $newWidth;
                    $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                }
                elseif ($this->height > $this->width)
                // *** Image to be resized is taller (portrait)
                {
                    $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                    $optimalHeight= $newHeight;
                }
                else
                // *** Image to be resizerd is a square
                {
                    if ($newHeight < $newWidth) {
                        $optimalWidth = $newWidth;
                        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
                    } else if ($newHeight > $newWidth) {
                        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
                        $optimalHeight= $newHeight;
                    } else {
                        // *** Sqaure being resized to a square
                        $optimalWidth = $newWidth;
                        $optimalHeight= $newHeight;
                    }
                }

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function getOptimalCrop($newWidth, $newHeight)
            {

                $heightRatio = $this->height / $newHeight;
                $widthRatio  = $this->width /  $newWidth;

                if ($heightRatio < $widthRatio) {
                    $optimalRatio = $heightRatio;
                } else {
                    $optimalRatio = $widthRatio;
                }

                $optimalHeight = $this->height / $optimalRatio;
                $optimalWidth  = $this->width  / $optimalRatio;

                return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
            }

            ## --------------------------------------------------------

            private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
            {
                // *** Find center - this will be used for the crop
                $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
                $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

                $crop = $this->imageResized;
                //imagedestroy($this->imageResized);

                // *** Now crop from center to exact requested size
                $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
                imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
            }

            ## --------------------------------------------------------

            public function saveImage($savePath, $imageQuality="100")
            {
                // *** Get extension
                $extension = strrchr($savePath, '.');
                $extension = strtolower($extension);

                switch($extension)
                {
                    case '.jpg':
                    case '.jpeg':
                        if (imagetypes() & IMG_JPG) {
                            imagejpeg($this->imageResized, $savePath, $imageQuality);
                        }
                        break;

                    case '.gif':
                        if (imagetypes() & IMG_GIF) {
                            imagegif($this->imageResized, $savePath);
                        }
                        break;

                    case '.png':
                        // *** Scale quality from 0-100 to 0-9
                        $scaleQuality = round(($imageQuality/100) * 9);

                        // *** Invert quality setting as 0 is best, not 9
                        $invertScaleQuality = 9 - $scaleQuality;

                        if (imagetypes() & IMG_PNG) {
                             imagepng($this->imageResized, $savePath, $invertScaleQuality);
                        }
                        break;

                    // ... etc

                    default:
                        // *** No extension - No save.
                        break;
                }

                imagedestroy($this->imageResized);
            }


            ## --------------------------------------------------------

        }
?>
Chloral answered 13/3, 2012 at 20:24 Comment(4)
This is awesome. No more tall images messing up my dynamically generated owl carousel. Thanks for sharing this!Simons
When using $resizeObj -> resizeImage(150, 150, 'crop'); Is the 150 the image dimensions in pixels?Boanerges
This is a perfect solution, thank you!Tegucigalpa
Thanks for this class. Solved my problem here. You can create images from any size with this class.Piliform
F
6

You load the image, resize it first so that it has the minimum side being 150, then you crop to the 150 width/height relative to the center. Then you just output your image:

WideImage::load('yourfile.png/jpg/...')
    ->resize(150, 150, 'outside', 'any')
    ->crop('center', 'center', 150, 150)
    ->output('png');

You find the sourcecode, documentation, online demos and the API documentation here: WideImage.

Let me know if you've still got questions.

Ferruginous answered 16/3, 2012 at 17:26 Comment(0)
R
4

It is very easy to use here is the class https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/timthumb/timthumb.php here are the params http://viralpatel.net/blogs/resize-image-dynamically-php/ I have tested looks works great

example is < img src="/script/timthumb.php?src=/some/path/myimage.png&w=100&h=80" alt="resized image" />

Remember that you should be careful to use this, If you do not create regex validation for input params you may have security vulnerability. That's why they deprecated this lib, but it works perfect.

Rookery answered 14/11, 2012 at 6:32 Comment(4)
Timbthumb is vulnerable for attacks.Kitts
There are multiple ways to be avoid from attacks.The idea is not to fix the security issues!Rookery
the link is busted: timthumb.googlecode.com/svn/trunk/timthumb.phpLusatian
Use storage.googleapis.com/google-code-archive-downloads/v2/…Rookery
C
2

I would store the thumbnails so that you only have to do it once and they can be cached. If your aspect ratio is fixed, I would scale them down to fit in a 200x200 box (there are some php answers here about that so I'll skip it). If the aspect ratio varies, I would use a safe value so that it always covers your 150x150 box (like 300x300).

Then I would set the thumbnail image as a background image for the image box in css and you get exactly the effect you want:

.img_box {
  background-repeat: no-repeat;
  background-position: center center;
  background-image: url(/path/to/image);
}

To enhance the experience for css3 capable browsers you can set:

background-size: cover;

to the box so that it fits exactly (maintaining aspect ratio).

Cornflakes answered 13/3, 2012 at 20:34 Comment(0)
S
1

Why not just do this with CSS and not have to use the server for any processing? There are a couple of ways to accomplish this using CSS. The Clip method is one I have used before, and a google search will bring you several results. Here is one site that covers this well

Stelu answered 6/3, 2012 at 10:19 Comment(1)
This isn't an answer. Can you give an example using CSS?Gianina
R
1
<?php
    $output_width =80;
    $output_height=80;

    if(isset($_GET['height'])){
       $output_height=$_GET['height'];
    }
     if(isset($_GET['width'])){
       $output_width=$_GET['width'];
    }

   $path = ( (isset($_REQUEST['path']))? $_REQUEST['path'] : "");
   //echo  $path;exit;
    $size_arr = getimagesize($path);
    if ($size_arr[2]==IMAGETYPE_GIF)
        $image = imagecreatefromgif($path);
    else if ($size_arr[2]==IMAGETYPE_JPEG)
        $image = imagecreatefromjpeg($path);
    else if ($size_arr[2]==IMAGETYPE_PNG)
        $image = imagecreatefrompng($path);
    else
        die_default_image();

    $tmpname = tempnam( sys_get_temp_dir() , "phptmp");

    resize_image($tmpname, $image, $size_arr, $output_width, $output_height);

    header('Content-Type: image/jpg');
    header('Content-Disposition: inline; filename="'.basename($path).'"');
    echo file_get_contents( $tmpname );
    unlink( $tmpname );
    die('');


function die_default_image()
{
    //43byte 1x1 transparent pixel gif
    header("content-type: image/gif");
    echo base64_decode("R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
}

function resize_image($thumbname, $image, $size_arr, $max_width, $max_height)//maintain aspect ratio
{
    $width  = $max_width;
    $height = $max_height;
    list($width_orig, $height_orig, $img_type) = $size_arr;
    $ratio_orig = $width_orig/$height_orig;

    if ($width/$height > $ratio_orig) {
       $width = floor($height*$ratio_orig);
    } else {
       $height = floor($width/$ratio_orig);
    }

    // Resample
    $tempimg = imagecreatetruecolor($width, $height);
    imagecopyresampled($tempimg, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
    imagejpeg($tempimg, $thumbname, 80);
}

if (!function_exists('sys_get_temp_dir')) {
  function sys_get_temp_dir() {
    if (!empty($_ENV['TMP'])) { return realpath($_ENV['TMP']); }
    if (!empty($_ENV['TMPDIR'])) { return realpath( $_ENV['TMPDIR']); }
    if (!empty($_ENV['TEMP'])) { return realpath( $_ENV['TEMP']); }
    $tempfile=tempnam(uniqid(rand(),TRUE),'');
    if (file_exists($tempfile)) {
    unlink($tempfile);
    return realpath(dirname($tempfile));
    }
  }
}
?>

Save the file as imageresize.php and put this file in your image folder and just use the code like this to show image

<img src="<?=base_url().'uploads/imageresize.php?path='.$image."&width=150 &height=150";?>" />

you can use this code to show images in different sizes.

Rossetti answered 12/3, 2012 at 8:48 Comment(0)
G
1

Here's my Image Resize Class. The Class can get the Result that you want (cropping/centered cropping/etc.)... and a lot more ;-)

I dont explain everything but if you got any questions just ask me.

<?php
final class Img {
    /**
     * Usage:
     * Img::resizeImage( 'sample.png', null, array( 'x' => 150, 'y' => 150 ) )
     * Outputs a Image
     * 
     * Img::resizeImage( 'sample.png', 'crop.jpg', array( 'x' => 200, 'y' => 200 ) )
     * Saves a Image
     *
     * @static
     * @param string $source
     * @param null|string $destination
     * @param array $options
     * @return void
     * @throws Exception
     */
    public static function resizeImage( $source, $destination = null, $options = array() ) {
        if( !file_exists( $source ) || ( is_string( $destination ) && !is_writable( dirname( $destination ) ) ) ) {
            throw new Exception( 'Quelldatei existiert nicht oder Zielverzeichnis ist nicht beschreibbar.' );
        }

        #@ini_set ('memory_limit', '64M' );

        $defaultOptions = array(
            'x' => 100,
            'y' => 100,
            'maxX' => 1000,
            'maxY' => 1000,
            'zoom_crop' => 1,
            'quality' => 90,
            'align' => 'c', // [c]enter, [b]ottom, [t]op, [l]eft, [r]ight
            'filters' => '',
            'sharpen' => 0,
            'canvas' => 'ffffff',
        );
        $options = array_merge( $defaultOptions, $options );

        $sData = getimagesize( $source );
        $origType = $sData[2];
        $mimeType = $sData['mime'];

        if( !preg_match( '/^image\/(?:gif|jpg|jpeg|png)$/i', $mimeType ) ) {
            throw new Exception( 'The image being resized is not a valid gif, jpg or png.' );
        }

        if( !function_exists( 'imagecreatetruecolor' ) ) {
            throw new Exception( 'GD Library Error: imagecreatetruecolor does not exist' );
        }

        if( function_exists( 'imagefilter' ) && defined( 'IMG_FILTER_NEGATE' ) ) {
            $imageFilters = array (
                    1 => array (IMG_FILTER_NEGATE, 0),
                    2 => array (IMG_FILTER_GRAYSCALE, 0),
                    3 => array (IMG_FILTER_BRIGHTNESS, 1),
                    4 => array (IMG_FILTER_CONTRAST, 1),
                    5 => array (IMG_FILTER_COLORIZE, 4),
                    6 => array (IMG_FILTER_EDGEDETECT, 0),
                    7 => array (IMG_FILTER_EMBOSS, 0),
                    8 => array (IMG_FILTER_GAUSSIAN_BLUR, 0),
                    9 => array (IMG_FILTER_SELECTIVE_BLUR, 0),
                    10 => array (IMG_FILTER_MEAN_REMOVAL, 0),
                    11 => array (IMG_FILTER_SMOOTH, 0),
            );
        }

        $destX = min( $options['x'], $options['maxX'] );
        $destY = min( $options['y'], $options['maxY'] );

        switch( $mimeType ) {
            case 'image/jpg':
            case 'image/jpeg':
            case 'image/pjgpg':
                $image = imagecreatefromjpeg( $source );
                break;
            case 'image/png':
                $image = imagecreatefrompng( $source );
                break;
            case 'image/gif':
                $image = imagecreatefromgif( $source );
                break;
        }

        if( !isset( $image ) ) {
            throw new Exception( 'Could not open Image' );
        }

        $width = imagesx( $image );
        $height = imagesy( $image );
        $originX = $originY = 0;

        if( $destX > 0 && $destY == 0 ) {
            $destY = floor( $height * ( $destX / $width ) );
        } else if( $destY > 0 && $destX == 0 ) {
            $destX = floor( $width * ( $destY / $height ) );
        }

        // scale down and add borders
        if( $options['zoom_crop'] == 3 ) {
            $finalY = $height * ( $destX / $width );

            if( $finalY > $destY ) {
                $destX = $width * ( $destY / $height );
            } else {
                $destY = $finalY;
            }
        }

        $canvas = imagecreatetruecolor( $destX, $destY );
        imagealphablending( $canvas, false );

        if( strlen( $options['canvas'] ) < 6 ) {
            $options['canvas'] = 'ffffff';
        }

        $canvasColorR = hexdec( substr( $options['canvas'], 0, 2 ) );
        $canvasColorG = hexdec( substr( $options['canvas'], 2, 2 ) );
        $canvasColorB = hexdec( substr( $options['canvas'], 2, 2 ) );

        // transparentes bild erstellen
        $color = imagecolorallocatealpha( $canvas, $canvasColorR, $canvasColorG, $canvasColorB, 127 );
        imagefill( $canvas, 0, 0, $color );

        // scale down and add borders
        if( $options['zoom_crop'] == 2 ) {
            $finalY = $height * ( $destX / $width );

            if( $finalY > $destY ) {
                $originX = $destX / 2;
                $destX = $width * ( $destY / $height );
                $originX = round( $originX - ( $destX / 2 ) );
            } else {
                $originY = $destY / 2;
                $destY = $finalY;
                $originY = round( $originY - ( $destY / 2 ) );
            }
        }

        // restore transparency blending
        imagesavealpha( $canvas, true );

        if( $options['zoom_crop'] > 0 ) {

            $srcX = $srcY = 0;
            $srcW = $width;
            $srcH = $height;

            $cmpX = $width / $destX;
            $cmpY = $height / $destY;

            // calculate x or y coordinate and width or height of source
            if( $cmpX > $cmpY ) {
                // breitformat
                $srcW = round( $width / $cmpX * $cmpY );
                $srcX = round( ( $width - ( $width / $cmpX * $cmpY ) ) / 2 );
            } elseif( $cmpY > $cmpX ) {
                $srcH = round( $height / $cmpY * $cmpX );
                $srcY = round( ( $height - ( $height / $cmpY * $cmpX ) ) / 2 );
            }

            // pos cropping
            if( strlen( $options['align'] ) ) {
                if( strpos( $options['align'], 't') !== false) {
                    $srcY = 0;
                }
                if( strpos( $options['align'], 'b') !== false) {
                    $srcY = $height - $srcH;
                }
                if( strpos( $options['align'], 'l') !== false) {
                    $srcX = 0;
                }
                if( strpos( $options['align'], 'r') !== false) {
                    $srcX = $width - $srcW;
                }
            }

            imagecopyresampled( $canvas, $image, $originX, $originY, $srcX, $srcY, $destX, $destY, $srcW, $srcH );

        } else {
            imagecopyresampled( $canvas, $image, 0, 0, 0, 0, $destX, $destY, $width, $height );
        }

        // @todo filtermöglichkeit über optionen ausbessern
        if( strlen( $options['filters'] ) && function_exists( 'imagefilter' ) && defined( 'IMG_FILTER_NEGATE' ) ) {
            // apply filters to image
            $filterList = explode( '|', $options['filters'] );
            foreach( $filterList as $fl ) {
                $filterSettings = explode (',', $fl);
                if (isset ($imageFilters[$filterSettings[0]])) {

                    for ($i = 0; $i < 4; $i ++) {
                        if (!isset ($filterSettings[$i])) {
                            $filterSettings[$i] = null;
                        } else {
                            $filterSettings[$i] = (int) $filterSettings[$i];
                        }
                    }
                    switch ($imageFilters[$filterSettings[0]][1]) {
                        case 1:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
                            break;
                        case 2:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
                            break;
                        case 3:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
                            break;
                        case 4:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
                            break;
                        default:
                            imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
                            break;
                    }
                }
            }
        }

        if( $options['sharpen'] > 0 && function_exists( 'imageconvolution' ) ) {
            $sharpenMatrix = array (
                            array (-1,-1,-1),
                            array (-1,16,-1),
                            array (-1,-1,-1),
                            );

            $divisor = 8;
            $offset = 0;

            imageconvolution( $canvas, $sharpenMatrix, $divisor, $offset );
        }

        //Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
        if( ( IMAGETYPE_PNG == $origType || IMAGETYPE_GIF == $origType ) &&
            function_exists( 'imageistruecolor' ) && !imageistruecolor( $image ) &&
            imagecolortransparent( $image ) > 0 ) {
            imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
        }

        if( null === $destination ) {
            header( "Cache-Control: no-store, no-cache, must-revalidate" );
            header( "Cache-Control: post-check=0, pre-check=0", false);
            header( "Pragma: no-cache" );
            header( "Expires: Sat, 26 Jul 1997 05:00:00 GMT" );
            header( "Last-Modified: " . date( "D, d M Y H:i:s" ) . " GMT" );

        }

        switch( $mimeType ) {
            case 'image/jpg':
            case 'image/jpeg':
            case 'image/pjgpg':
                if( null === $destination ) {
                    header("Content-type: image/jpeg");
                }
                @imagejpeg( $canvas, $destination, $options['quality'] );
                break;
            case 'image/png':
                if( null === $destination ) {
                    header("Content-type: image/png");
                }
                @imagepng( $canvas, $destination, floor( $options['quality'] * 0.09 ) );
                break;
            case 'image/gif':
                if( null === $destination ) {
                    header("Content-type: image/gif");
                }
                @imagegif( $canvas, $destination );
                break;
            default:
                throw new Exception( 'Fehler beim schreiben' );
                break;
        }

        imagedestroy( $canvas );
        imagedestroy( $image );
    }
}
Gonyea answered 12/3, 2012 at 9:7 Comment(0)
C
1

I don't know this fully but once I created a program which would view us thumbnail images for our images. And the code goes like this:

$src=imagecreatefromjpg("file.jpg");
$dest=imagecreatetruecolor($destwidth,$destheight);
$src1=imagecopyresized($dest,$src,0,0,0,0,$destwidth,$destheight,$widthresource,$heightresource);
echo imagejpeg($dest);

changing the parameters of imagecopyresized which are set to 0,0,0,0 here will crop your image from x1,y1 to x2,y2 Hope this helps

Clichy answered 14/3, 2012 at 4:42 Comment(0)
D
0

I have a shell script in place that does exactly what you need with ImageMagick:

#!/bin/sh
SOURCE='/path/to/img'
FILE='myfile.jpg'

convert $SOURCE/$FILE -thumbnail 150x150^\> -quality 85% \
        -gravity center -extent 150x150 ${SOURCE}150/$FILE
  • This resizes to a box covering 150x150 - the ^ after 150x150 is essential!
  • The -thumbnail option strips all meta-information except for color profiles and is very fast.
  • Then it cuts a box with 150x150 from the center (-gravity center -extent 150x150) - exactly what you want.
  • In addition I set -quality 85% which should be plenty while reducing file size a lot.
  • In this example I take the image from an img directory and write the thumbnail with the same filename to a img150 directory right next to it.

Experiment for best results.

I had help from:
http://www.imagemagick.org/Usage/files/
http://www.imagemagick.org/Usage/resize/
http://www.imagemagick.org/script/command-line-options.php#thumbnail

Dante answered 12/3, 2012 at 12:53 Comment(0)
A
0

As a few have mentioned, this can be done with CSS if you're not saving the image. Although load times will be hurt (downloading a 800x600 image vs downloading a 150x150 image).

HTML:

<div class="imgHold">
     <img src="imgSrc.jpg" />
</div>

CSS:

div{
     overflow:hidden;
}
img{
    width:150px;
    height:200px;
    margin-top:-25px;
}
Antisana answered 13/3, 2012 at 7:46 Comment(0)
F
0

you can do this with jquery. i assume you have a classname for the images that you want to show cropped. for example it might be ".cropmyimage", here's the code:

var objheight = 150;
var objwidth = 150;
$(".cropmyimage").each(function(){      
    var elem = $(this);
    elem.wrap("<div class='cropperdiv'></div>");
    var t = new Image();        
    t.src = elem.attr("src");
    t.onload = function(){      
        var ratio1 = objwidth/objheight; 
        var ratio2 = t.width/t.height;          
        var newheight=0;
        var newwidth=0;
        if(ratio1 < ratio2){
            newheight = parseInt(objheight);
            newwidth = parseInt(objheight * ratio2);                        
        }else{
            newheight = parseInt(objwidth / ratio2);
            newwidth = "width",objwidth;        
        }                   
        elem.width(newwidth).height(newheight).css("margin-left",(objwidth-newwidth)/2).css("margin-top",(objheight-newheight)/2);          
    }
    elem.parent("div.cropperdiv").css("overflow","hidden").width(objwidth).height(objheight);
});
Folderol answered 14/3, 2012 at 23:16 Comment(0)
T
0

Look into WideImage, an open-source PHP library for image manipulation. Could get a simple as

WideImage::load('pic.jpg')->resize(150, 150, 'outside')->output('jpg');

http://wideimage.sourceforge.net/

Tropophilous answered 15/3, 2012 at 20:46 Comment(1)
That variant does not work, but you can find a working version here.Ferruginous
C
0

DYNAMIC IMAGE RESIZING SCRIPT - V2 The following script will take an existing JPG image, and resize it using set options defined in your .htaccess file (while also providing a nice clean URL to use when referencing the images) Images will be cached, to reduce overhead, and will be updated only if the image is newer than it's cached version.

The original script is from Timothy Crowe's 'veryraw' website, with caching additions added by Trent Davies: http://veryraw.com/history/2005/03/image-resizing-with-php/ <Not Work>

Further modifications to include antialiasing, sharpening, gif & png support, plus folder structues for image paths, added by Mike Harding http://sneak.co.nz <Not Work>

For instructions on use, head to http://sneak.co.nz <Not Work>

<?php

// max_width and image variables are sent by htaccess

$max_height = 1000;

$image = $_GET["imgfile"];
$max_width = $_GET["max_width"];
if (strrchr($image, '/')) {
    $filename = substr(strrchr($image, '/'), 1); // remove folder references
} else {
    $filename = $image;
}

$size = getimagesize($image);
$width = $size[0];
$height = $size[1];

// get the ratio needed
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;

// if image already meets criteria, load current values in
// if not, use ratios to load new size info
if (($width <= $max_width) && ($height <= $max_height) ) {
    $tn_width = $width;
    $tn_height = $height;
} else if (($x_ratio * $height) < $max_height) {
    $tn_height = ceil($x_ratio * $height);
    $tn_width = $max_width;
} else {
    $tn_width = ceil($y_ratio * $width);
    $tn_height = $max_height;
}

/* Caching additions by Trent Davies */
// first check cache
// cache must be world-readable
$resized = 'cache/'.$tn_width.'x'.$tn_height.'-'.$filename;
$imageModified = @filemtime($image);
$thumbModified = @filemtime($resized);

header("Content-type: image/jpeg");

// if thumbnail is newer than image then output cached thumbnail and exit
if($imageModified<$thumbModified) {
    header("Last-Modified: ".gmdate("D, d M Y H:i:s",$thumbModified)." GMT");
    readfile($resized);
    exit;
}

// read image
$ext = substr(strrchr($image, '.'), 1); // get the file extension
switch ($ext) { 
    case 'jpg':     // jpg
        $src = imagecreatefromjpeg($image) or notfound();
        break;
    case 'png':     // png
        $src = imagecreatefrompng($image) or notfound();
        break;
    case 'gif':     // gif
        $src = imagecreatefromgif($image) or notfound();
        break;
    default:
        notfound();
}

// set up canvas
$dst = imagecreatetruecolor($tn_width,$tn_height);

imageantialias ($dst, true);

// copy resized image to new canvas
imagecopyresampled ($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);

/* Sharpening addition by Mike Harding */
// sharpen the image (only available in PHP5.1)
if (function_exists("imageconvolution")) {
    $matrix = array(    array( -1, -1, -1 ),
                    array( -1, 32, -1 ),
                    array( -1, -1, -1 ) );
    $divisor = 24;
    $offset = 0;

    imageconvolution($dst, $matrix, $divisor, $offset);
}

// send the header and new image
imagejpeg($dst, null, -1);
imagejpeg($dst, $resized, -1); // write the thumbnail to cache as well...

// clear out the resources
imagedestroy($src);
imagedestroy($dst);

?>
Cyb answered 26/11, 2022 at 10:4 Comment(0)
K
-1

This is exactly you´re looking for, and one step futher, caching thumbs:

Check http://phpthumb.gxdlabs.com/

You can use this script as script.php?img=image.jpg&size=100, in this case, they are on the same folder of the script.

 <?php

    require_once '/path/to/ThumbLib.inc.php';  
    $filename = $_GET['img'];
    $path = "/upload/item/";
    $thumb = $_GET['size'];

    // Just let specific values 
    $sizeThumb = array('20','40','50','80','100','120','150');

    if(in_array($thumb,$sizeThumb)){
      $maxWidth = $thumb;
      $maxHeight = $thumb;
    } else { header('Status: 404 Not Found');   die; }   
    $pathUrl = _ROOT_FOLDER.'/thumbs/autothumb-'.$thumb.'-'.$filename;

    if(!file_exists(_ROOT_FOLDER.$path.$filename)) { header('Status: 404 Not Found');   die; } 

    if(!file_exists($pathUrl) ){

     $max = PhpThumbFactory::create(_ROOT_FOLDER.$path.$filename);
     $max->adaptiveResize($maxWidth,$maxHeight)->save($pathUrl);
     }

    header('Content-type: image/jpeg');    
    readfile($pathUrl);  

?> 
Kolo answered 16/3, 2012 at 13:57 Comment(1)
Adaptive resize produces the output you´re looking forKolo
C
-3

I think a simple solution with no stress and processin work would be with css:

1) Apply a class which will give you a cropped image. Do this with help of negative margin. I haven'nt used the exact margin use it as you require. 2) On hover overwrite the marging attribute, so that it will give you the real image.

css:
 <style>
   .crop:hover{
       margin:0;

    }
    .crop {
        margin:-100px -15px -40px -55px;
     }
</style>

html:

<img class="crop" src="image.jpg" />
Curmudgeon answered 17/3, 2012 at 17:44 Comment(1)
Resizing images with CSS will affect the performance. Especially noticed when using transitions.Protoxide
L
-5

just use <img src='source' width="150" height="150" /> it will resize image. though it will not preferable because it cause burden on browser.

Losse answered 6/3, 2012 at 10:22 Comment(2)
This won't maintain the aspect ratio of the image though. Right?Pissarro
yup.As i say its not preferable.Losse

© 2022 - 2024 — McMap. All rights reserved.