I want to retrieve image from a URL, resize it and save it to folder.
I have this code to retrieve image from url :
$url = 'http://www.example.com/image/test.jpg';
$img = 'images/newtest.jpg';
file_put_contents($img, file_get_contents($url));
The problem is that before doing file_put_contents
, I want to resize the image. How can I do it with php? Please Help me, I have searched on the internet but ended up with unclear explanation.
You can use the GD2 or ImageMagick libraries.
Here is how you can do it if imagemagick is installed on your server...
$url = 'http://www.example.com/image/test.jpg';
$img = 'images/newtest.jpg';
file_put_contents($img, file_get_contents($url));
$image = new Imagick( $img );
$imageprops = $image->getImageGeometry();
if ($imageprops['width'] <= 200 && $imageprops['height'] <= 200) {
// don't upscale
} else {
$image->resizeImage(200,200, imagick::FILTER_LANCZOS, 0.9, true);
}
You will need to take a look at the GD Image Processing Library's documentation, most specifically at the imagecreatefromjpeg()
function.
An example function doing the trick can look like this:
function resize_jpeg( $original_image, $new_height, $new_width, $filename )
{
// Resize the original image
$image_resized = imagecreatetruecolor($new_width, $new_height);
$image_tmp = imagecreatefromjpeg ($original_image);
imagecopyresampled($image_resized, $image_tmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_resized, $filename.".jpg", 100);
imagedestroy($image_resized);
}
The function basically creates an image reference with the new height, loads the old one and then resamples it. Instead of jpeg
you can use png
and gif
too. Be careful, as GD cannot properly resample animated GIF files.
original_image
is a file path of the image to load. new_width
and new_height
are integers of the target width and height, respectively. filename
is the target filename, without the .jpg
extension in this example.