Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save an image Resized with PHP

I am working on improving my Facebook app. I need to be able to resize an image, then save it to a directory on the server. This is the code I have to resize:

<?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);
?>

My question is, how would I save this resized image? Would I need to? Is there a way to manipulate the resized image without saving it?

like image 223
Zac Brown Avatar asked Sep 02 '26 13:09

Zac Brown


1 Answers

According to the manual on imagejpeg(), the optional second parameter can specify a file name, which it will be written into.

Filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

To skip this argument in order to provide the quality parameter, use NULL.

It's usually a good idea to write the results to disk for some basic caching, so that not every incoming request leads to a (resource intensive) GD call.

like image 150
Pekka Avatar answered Sep 04 '26 02:09

Pekka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!