Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imagecrop without saving the image

Tags:

php

crop

I have a bunch of product preview images, but they are not the same dimensions.

So i wonder, is it possible to crop an image on the go, without saving it?

These two links should show what i mean:

http://xn--nstvedhandel-6cb.dk/alpha_1/?side=vis_annonce&id=12

http://xn--nstvedhandel-6cb.dk/alpha_1/?side=vis_annonce&id=13

like image 339
Patrick Reck Avatar asked Aug 31 '12 08:08

Patrick Reck


1 Answers

Yes it's possible here's how i do it:

//Your Image
$imgSrc = "image.jpg";
list($width, $height) = getimagesize($imgSrc);
$myImage = imagecreatefromjpeg($imgSrc);

// calculating the part of the image thumbnail
if ($width > $height)
{
    $y = 0;
    $x = ($width - $height) / 2;
    $smallestSide = $height;
 } 
 else
 {
    $x = 0;
    $y = ($height - $width) / 2;
    $smallestSide = $width;
 }

 // copying the part into thumbnail
 $thumbSize = 100;
 $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
 imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

 //final output
 header('Content-type: image/jpeg');
 imagejpeg($thumb);

This is not a verry light operation, like the others i also reccomend you to save the thumbnail after creating it to your file system.

You might wanna check out PHP's GD library.

like image 172
RTB Avatar answered Sep 28 '22 07:09

RTB