Thursday, February 24, 2011

Save image from a image URL

Hi,

Yet again a GD library based post. You can use simple CURL and few GD library function to extract an image from a given URL. The basic concept in achieving this to extract the content of the file using CURL. This may sound complicated but it is not. CURL is used to extract the page content of an external URL. In our case the URL is an image. So it will extract the content of the image. After we have that we use a php function and few other GD functions to save that as an image file:

Here is how I had done that:



<?php

$destination_file="my_pic.gif";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, "<URL_OF_THE_IMAGE>");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
curl_close($ch);
$newImg = imagecreatefromstring($fileContents);
if(strtolower($ext)=="png"){ imagepng($newImg, $destination_file,9);}
elseif(strtolower($ext)=="gif"){imagegif($newImg, $destination_file,100);}
else{ imagejpeg($newImg, $destination_file,100);}
?>

$destination_file is the name file I want to save the image URL to.

Post in your comments if any queries :)


No comments:

Post a Comment