How to download a remote image using GD or cURL

This a PHP Class useful if you need to download images from a remote location. You can choose between 2 methods to retrieve the image: using GD or cURL.

Here is the class (I will explain you how it works below):

  1. <?php  
  2. class  GetImage {  
  3.   
  4. var   $source ;  
  5. var   $save_to ;  
  6. var   $set_extension ;  
  7. var   $quality ;  
  8.   
  9. function  download( $method  =  'curl'// default method: cURL   
  10. {  
  11. $info  = @ GetImageSize ( $this ->source);  
  12. $mime  =  $info [ 'mime' ];  
  13.   
  14. // What sort of image?   
  15. $type  =  substr ( strrchr ( $mime'/' ), 1);  
  16.   
  17. switch  ( $type )  
  18. {  
  19. case   'jpeg' :  
  20.     $image_create_func  =  'ImageCreateFromJPEG' ;  
  21.     $image_save_func  =  'ImageJPEG' ;  
  22.     $new_image_ext  =  'jpg' ;  
  23.   
  24.     // Best Quality: 100   
  25.     $quality  = isSet( $this ->quality) ?  $this ->quality : 100;  
  26.     break ;  
  27.   
  28. case   'png' :  
  29.     $image_create_func  =  'ImageCreateFromPNG' ;  
  30.     $image_save_func  =  'ImagePNG' ;  
  31.     $new_image_ext  =  'png' ;  
  32.   
  33.     // Compression Level: from 0  (no compression) to 9   
  34.     $quality  = isSet( $this ->quality) ?  $this ->quality : 0;  
  35.     break ;  
  36.   
  37. case   'bmp' :  
  38.     $image_create_func  =  'ImageCreateFromBMP' ;  
  39.     $image_save_func  =  'ImageBMP' ;  
  40.     $new_image_ext  =  'bmp' ;  
  41.     break ;  
  42.   
  43. case   'gif' :  
  44.     $image_create_func  =  'ImageCreateFromGIF' ;  
  45.     $image_save_func  =  'ImageGIF' ;  
  46.     $new_image_ext  =  'gif' ;  
  47.     break ;  
  48.   
  49. case   'vnd.wap.wbmp' :  
  50.     $image_create_func  =  'ImageCreateFromWBMP' ;  
  51.     $image_save_func  =  'ImageWBMP' ;  
  52.     $new_image_ext  =  'bmp' ;  
  53.     break ;  
  54.   
  55. case   'xbm' :  
  56.     $image_create_func  =  'ImageCreateFromXBM' ;  
  57.     $image_save_func  =  'ImageXBM' ;  
  58.     $new_image_ext  =  'xbm' ;  
  59.     break ;  
  60.   
  61. default :  
  62.     $image_create_func  =  'ImageCreateFromJPEG' ;  
  63.     $image_save_func  =  'ImageJPEG' ;  
  64.     $new_image_ext  =  'jpg' ;  
  65. }  
  66.   
  67. if (isSet( $this ->set_extension))  
  68. {  
  69. $ext  =  strrchr ( $this ->source,  "." );  
  70. $strlen  =  strlen ( $ext );  
  71. $new_name  =  basename ( substr ( $this ->source, 0, - $strlen )). '.' . $new_image_ext ;  
  72. }  
  73. else   
  74. {  
  75. $new_name  =  basename ( $this ->source);  
  76. }  
  77.   
  78. $save_to  =  $this ->save_to. $new_name ;  
  79.   
  80.     if ( $method  ==  'curl' )  
  81.     {  
  82.     $save_image  =  $this ->LoadImageCURL( $save_to );  
  83.     }  
  84.     elseif ( $method  ==  'gd' )  
  85.     {  
  86.     $img  =  $image_create_func ( $this ->source);  
  87.   
  88.         if (isSet( $quality ))  
  89.         {  
  90.            $save_image  =  $image_save_func ( $img$save_to$quality );  
  91.         }  
  92.         else   
  93.         {  
  94.            $save_image  =  $image_save_func ( $img$save_to );  
  95.         }  
  96.     }  
  97.   
  98.     return   $save_image ;  
  99. }  
  100.   
  101. function  LoadImageCURL( $save_to )  
  102. {  
  103. $ch  =  curl_init ( $this ->source);  
  104. $fp  =  fopen ( $save_to"wb" );  
  105.   
  106. // set URL and other appropriate options   
  107. $options  =  array (CURLOPT_FILE =>  $fp ,  
  108.                  CURLOPT_HEADER => 0,  
  109.                  CURLOPT_FOLLOWLOCATION => 1,  
  110.                  CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough)   
  111.   
  112. curl_setopt_array($ch$options );  
  113.   
  114. curl_exec ( $ch );  
  115. curl_close ( $ch );  
  116. fclose($fp );  
  117. }  
  118. }  
  119. ?>  
<?php
class GetImage {

var $source;
var $save_to;
var $set_extension;
var $quality;

function download($method = 'curl') // default method: cURL
{
$info = @GetImageSize($this->source);
$mime = $info['mime'];

// What sort of image?
$type = substr(strrchr($mime, '/'), 1);

switch ($type)
{
case 'jpeg':
    $image_create_func = 'ImageCreateFromJPEG';
    $image_save_func = 'ImageJPEG';
	$new_image_ext = 'jpg';

	// Best Quality: 100
	$quality = isSet($this->quality) ? $this->quality : 100;
    break;

case 'png':
    $image_create_func = 'ImageCreateFromPNG';
    $image_save_func = 'ImagePNG';
	$new_image_ext = 'png';

	// Compression Level: from 0  (no compression) to 9
	$quality = isSet($this->quality) ? $this->quality : 0;
    break;

case 'bmp':
    $image_create_func = 'ImageCreateFromBMP';
    $image_save_func = 'ImageBMP';
	$new_image_ext = 'bmp';
    break;

case 'gif':
    $image_create_func = 'ImageCreateFromGIF';
    $image_save_func = 'ImageGIF';
	$new_image_ext = 'gif';
    break;

case 'vnd.wap.wbmp':
    $image_create_func = 'ImageCreateFromWBMP';
    $image_save_func = 'ImageWBMP';
	$new_image_ext = 'bmp';
    break;

case 'xbm':
    $image_create_func = 'ImageCreateFromXBM';
    $image_save_func = 'ImageXBM';
	$new_image_ext = 'xbm';
    break;

default:
	$image_create_func = 'ImageCreateFromJPEG';
    $image_save_func = 'ImageJPEG';
	$new_image_ext = 'jpg';
}

if(isSet($this->set_extension))
{
$ext = strrchr($this->source, ".");
$strlen = strlen($ext);
$new_name = basename(substr($this->source, 0, -$strlen)).'.'.$new_image_ext;
}
else
{
$new_name = basename($this->source);
}

$save_to = $this->save_to.$new_name;

    if($method == 'curl')
	{
    $save_image = $this->LoadImageCURL($save_to);
	}
	elseif($method == 'gd')
	{
	$img = $image_create_func($this->source);

	    if(isSet($quality))
	    {
		   $save_image = $image_save_func($img, $save_to, $quality);
		}
		else
		{
		   $save_image = $image_save_func($img, $save_to);
		}
	}

	return $save_image;
}

function LoadImageCURL($save_to)
{
$ch = curl_init($this->source);
$fp = fopen($save_to, "wb");

// set URL and other appropriate options
$options = array(CURLOPT_FILE => $fp,
                 CURLOPT_HEADER => 0,
                 CURLOPT_FOLLOWLOCATION => 1,
	             CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough)

curl_setopt_array($ch, $options);

curl_exec($ch);
curl_close($ch);
fclose($fp);
}
}
?>
Variables Info var $source - The URL to the image (ex: http://www.domain.com/images/logo.jpg).

var $save_to - The path to the folder where the image will be saved (with trailing slash at the end)

var $set_extension - Are there any cases when the images you’re downloading have a wrong extension or do not have an extension at all? Consider turning this to “true”. Based on the mime type of the image, an extension is automatically assigned to the file.

var $quality - This is the 3rd argument that is passed to the image saver function. It is used for JPEG (from 0 to 100) or PNG (from 0 to 9) images.

How it works?

After initializing the class and the necessary variables are set, download() is called. Here the GetImageSize() function is used to obtain information regarding the image. We are interested in the mime-type from which he have to extract the type of image. Based on $type we will set some variables such: $image_create_func, $image_save_func, $new_image_ext (useful if $set_extension is set to ‘true’) and even $quality for ‘JPEG’ and ‘PNG’. The first 2 variables are needed in case we will use GD to download the image.

If $this->set_extension is not set, the saved image will have exactly the same name and extension (if any) as the remote image. If it is set, then we add $new_image_ext to the file name (could be the same as the remote one):

  1. if (isSet( $this ->set_extension))  
  2. {  
  3. $ext  =  strrchr ( $this ->source,  "." );  
  4. $strlen  =  strlen ( $ext );  
  5. $new_name  =  basename ( substr ( $this ->source, 0, - $strlen )). '.' . $new_image_ext ;  
  6. }  
  7. else   
  8. {  
  9. $new_name  =  basename ( $this ->source);  
  10. }  
if(isSet($this->set_extension))
{
$ext = strrchr($this->source, ".");
$strlen = strlen($ext);
$new_name = basename(substr($this->source, 0, -$strlen)).'.'.$new_image_ext;
}
else
{
$new_name = basename($this->source);
}

Set the full path where the image will be saved (filename + save folder):

  1. $save_to  =  $this ->save_to. $new_name ;  
$save_to = $this->save_to.$new_name;

Now, some functions would be called based on the $method value (could be ‘gd or ‘curl’):

  1.    if ( $method  ==  'curl' )  
  2. {  
  3.    $save_image  =  $this ->LoadImageCURL( $save_to );  
  4. }  
  5. elseif ( $method  ==  'gd' )  
  6. {  
  7. $img  =  $image_create_func ( $this ->source);  
  8.   
  9.     if (isSet( $quality ))  
  10.     {  
  11.        $save_image  =  $image_save_func ( $img$save_to$quality );  
  12.     }  
  13.     else   
  14.     {  
  15.        $save_image  =  $image_save_func ( $img$save_to );  
  16.     }  
  17. }  
   if($method == 'curl')
	{
    $save_image = $this->LoadImageCURL($save_to);
	}
	elseif($method == 'gd')
	{
	$img = $image_create_func($this->source);

	    if(isSet($quality))
	    {
		   $save_image = $image_save_func($img, $save_to, $quality);
		}
		else
		{
		   $save_image = $image_save_func($img, $save_to);
		}
	}

If we choose ‘gd’ the LoadImageCURL() function will be called with one argument, $save_to, representing the full path where the image would be saved.

The curl_unit() is called with the ‘url’ argument ($this->source). The session is initialized and returns a cURL handle for use with curl_setopt_array(), curl_exec() and curl_close() functions. The next thing to do is to open the remote image for writing using fopen():

  1. $ch  =  curl_init ( $this ->source);  
  2. $fp  =  fopen ( $save_to"wb" );  
$ch = curl_init($this->source);
$fp = fopen($save_to, "wb");

The function curl_setopt_array() sets multiple options for a cURL transfer without repetitively calling curl_setopt():

  1. // set URL and other appropriate options   
  2. $options  =  array (CURLOPT_FILE =>  $fp ,  
  3.                  CURLOPT_HEADER => 0,  
  4.                  CURLOPT_FOLLOWLOCATION => 1,  
  5.                  CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough)   
  6.   
  7. curl_setopt_array($ch$options );  
// set URL and other appropriate options
$options = array(CURLOPT_FILE => $fp,
                 CURLOPT_HEADER => 0,
                 CURLOPT_FOLLOWLOCATION => 1,
	             CURLOPT_TIMEOUT => 60); // 1 minute timeout (should be enough)

curl_setopt_array($ch, $options);

Now we need to grab the URL and pass it to the browser:

  1. curl_exec ( $ch );  
curl_exec($ch);

The last things to do is closing both the cURL resource (to free up system resources) and the open file pointer:

  1. curl_close ( $ch );  
  2. fclose($fp );  
curl_close($ch);
fclose($fp);

The image is now saved in the specified folder.

Now, let’s see how we can download the image using the ‘gd’ method! We’ll call the function needed to create the image from URL ($image_create_func). It’s used to return an image identifier representing the image obtained from the given URL:

  1. // possible values: ImageCreateFromJPEG, ImageCreateFromPNG etc.   
  2. $img  =  $image_create_func ( $this ->source);  
// possible values: ImageCreateFromJPEG, ImageCreateFromPNG etc.
$img = $image_create_func($this->source);

The next function used ($image_save_func) is used to create the image from the given image ($img). Another aspect here is the $quality variable. For JPEG images, the value ranges from 0 (worst quality, smaller file) to 100 (best quality). The default is the default IJG quality value (about 75). As for the PNG images, the range is from 0 (no compression) to 9.

  1. if (isSet( $quality ))  
  2. {  
  3. // possible values: ImageJPEG, ImagePNG etc.   
  4. $save_image  =  $image_save_func ( $img$save_to$quality );  
  5. }  
  6. else   
  7. {  
  8. $save_image  =  $image_save_func ( $img$save_to );  
  9. }  
if(isSet($quality))
{
// possible values: ImageJPEG, ImagePNG etc.
$save_image = $image_save_func($img, $save_to, $quality);
}
else
{
$save_image = $image_save_func($img, $save_to);
}

Here’s an example of how you can use this class:

  1. <?php  
  2. include_once   'class.get.image.php' ;  
  3.   
  4. // initialize the class   
  5. $image  =  new  GetImage;  
  6. $image ->source =  'http://l.yimg.com/a/i/ww/beta/y3.gif' ;  
  7. $image ->save_to =  'images/'// with trailing slash at the end   
  8.   
  9. $get  =  $image ->download( 'gd' );  // using GD   
  10.   
  11. if ( $get )  
  12. {  
  13. echo   'The image has been saved.' ;  
  14. }  
  15. ?>  
<?php
include_once 'class.get.image.php';

// initialize the class
$image = new GetImage;
$image->source = 'http://l.yimg.com/a/i/ww/beta/y3.gif';
$image->save_to = 'images/'; // with trailing slash at the end

$get = $image->download('gd'); // using GD

if($get)
{
echo 'The image has been saved.';
}
?>

NOTE: Make sure the folder where the image will be saved is writable (chmod 0777).

Happy coding!

Tracback: http://www.bitrepository.com/web-programming/php/download-image.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值