user1012181
user1012181

Reputation: 8726

Image cannot resize using PHP

I'm trying to resize an image that I copy from Flickr. But it seems I'm getting the original size itself. Here is my code:

$img = Input::get('FlickrUrl');
$filename = gmdate('Ymdhis', time());
copy($img, $_SERVER["DOCUMENT_ROOT"].'/upload/'.$filename.'.jpeg');
$newImg = '/upload/'.$filename.'.jpeg';
list($CurWidth, $CurHeight) = getimagesize($_SERVER["DOCUMENT_ROOT"].$newImg);

$width = $CurWidth;
$height = $CurHeight;
$image_ratio = $CurWidth / $CurHeight;

//resize image according to container
$container_width = 300;
$container_height = 475;

if($CurWidth > $container_width)
{
    $CurWidth = $container_width;
    $CurHeight = $CurWidth / $image_ratio;
}
if($CurHeight > $container_height)
{
    $CurHeight = $container_height;
    $CurWidth = $CurHeight * $image_ratio;
}

if($CurWidth < $container_width)
{
    $CurWidth = $container_width;
    $CurHeight = $CurWidth / $image_ratio;
}
if($CurHeight < $container_height){
    $CurHeight = $container_height;
    $CurWidth = $CurHeight * $image_ratio;
}

$img_orginal = $_SERVER["DOCUMENT_ROOT"].'/upload/'.$filename.'.jpeg';
$img_org = ImageCreateFromJPEG($img_orginal);
$NewCanves  = imagecreatetruecolor($CurWidth, $CurHeight);
imagecopyresized($NewCanves, $img_org, 0, 0, 0, 0, $CurWidth, $CurHeight, $width, $height);
$finalImg = '/upload/'.$filename.'.jpeg';


return Response::json(["success"=>"true", "images"=>$finalImg, "width"=>$CurWidth, "height"=>$CurHeight]);

First I copy the Image from the URL, saves it in my server and then trying to resize it. Can't understand whats wrong with this code.

Upvotes: 1

Views: 137

Answers (2)

Limon Monte
Limon Monte

Reputation: 54379

Try intervention/image package with great Laravel integration:

// open an image file
$img = Image::make('FlickrUrl');

// now you are able to resize the instance
$img->resize($container_width, $container_height);

// finally we save the image as a new file
$img->save('/upload/'.$filename.'.jpeg');    

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

The problem here is you don't save your file. After:

imagecopyresized($NewCanves, $img_org, 0, 0, 0, 0, $CurWidth, $CurHeight, $width, $height);
$finalImg = '/upload/'.$filename.'.jpeg'

you should add:

imagejpeg($NewCanves, $finalImg);

to save it in filesystem

Upvotes: 1

Related Questions