`

How to download a remote image using GD or cURL

    博客分类:
  • php
阅读更多

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
分享到:
评论

相关推荐

    Spring.REST.1484208242

    Spring REST is a practical guide for designing and developing RESTful APIs using the Spring Framework. This book walks you through the process of designing and building a REST application while taking...

    c++封装curl,实现get,post,download

    c++封装了curl的get,post,download

    支持WINDOWS XP的CURL 最后版本7.56.1

    经过多版本尝试,CURL 最后支持WINDOWS XP的版本是7.56.1,此资源包为SRC包,与编译BIN包,并且带有LIBSSH2与OPENSSL 1.1.1q,openssl 0.9.8, zlib1.2.12,在7.56.1以后的版本都已经不支持WINDOWS XP,因为其已经...

    curl下载curl包下载

    curl下载curl包下载

    IRI2012电离层模型 matlab代码

    Windows users can download cURL from http://curl.haxx.se/download.html. You'll have to download the appropriate executable for your operating system, and I recommend putting it in the same directory ...

    windows版curl

    windows版curl命令 Startup: -V, --version display the version of Wget and exit. -h, --help print this help. -b, --background go to background after startup. -e, --execute=COMMAND execute a `....

    curl命令详解curl命令详解curl命令详解curl命令详解

    curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令详解curl命令...

    cURL(curl-8.4.0)

    curl-8.4.0.tar.gz curl-8.4.0.zip

    curl windows版

    curl windows版,和linux下效果一样,可方便快速地进行http协议的调试,包括get、post、文件上传、下载等。

    curl win64 curl安装包

    Curl命令可以通过命令行的方式,执行Http请求。...在官网处下载工具包:http://curl.haxx.se/download.html 下载好后解压 配置环境变量 CURL_HOME指到文件目录 path指到bin目录 在cmd中输入curl --help

    curl_docker_image

    curl_docker_image如有任何疑问,疑问或疑虑,请发送至: curldocker@blairjames.com 功能齐全的Curl实现。 精益求精。 CI / CD的构建,监视和维护。 从最新的稳定来源最新编译: : 像本地curl一样docker run ,只需...

    everything-curl.pdf

    Everything curl is an extensive guide to everything there is to know about curl, the project, the command-line tool, the library, how everything started and how it came to be what it is today. How we ...

    curl-7.53.1_spendrhy_curl_aix7.1安装curl_

    curl工具,可以方便调试url,简单易用的url调试工具

    Curl.zip_C++ curl_DEMO_c++ curl_curl_curl c++

    windows下C开发CURL的Demo

    Elasticsearch in Action(Manning,2015)

    Elasticsearch in Action teaches you how to build scalable search applications using Elasticsearch. You'll ramp up fast, with an informative overview and an engaging introductory example. Within the ...

    Everything curl

    Everything curl is an extensive guide to everything there is to know about curl, the project, the command-line tool, the library, how everything started and how it came to be what it is today. How we ...

    WWW-Curl-4.15.tar_curl_www_www-curl_Perl_

    4.15的版本的www-curl,老一点的版本,根据自己选择下载

    curl7.52.1库

    curl7.52.1库

    curl-7.59.0.zip

    Curl is a command-line tool for transferring data specified with URL syntax. Find out how to use curl by reading [the curl.1 man page](https://curl.haxx.se/docs/manpage.html) or [the MANUAL document]...

Global site tag (gtag.js) - Google Analytics