`

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

相关推荐

    curl工具下载(windows版)

    **curl工具概述** `curl` 是一个强大的命令行工具,用于传输数据,支持众多协议,如HTTP、HTTPS、FTP、FTPS、SMTP、SFTP等。它的灵活性在于它可以通过URL语法来操作各种网络资源,无需图形用户界面。`curl` 在开发...

    curl下载curl包下载

    官网地址是&lt;https://curl.se/download.html&gt;。在网站上,你可以找到适用于不同操作系统的源代码包、预编译二进制文件以及特定平台的安装包。 对于Windows用户,可以选择下载`.exe`可执行文件,这是一个便携式版本,...

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

    Curl.zip 文件包含了一个在Windows环境下使用C++开发的CURL库示例程序。CURL是一个流行的开源库,用于在各种编程语言中处理URL传输,包括文件上传、下载、HTTP、HTTPS、FTP等网络协议。这个C++ DEMO将帮助我们理解...

    支持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,因为其已经...

    安卓android版本的curl库

    要在Android项目中使用Curl库,开发者需要将对应的库文件(libcurl.a)添加到项目的jniLibs目录下,并在Java代码中通过JNI(Java Native Interface)调用Curl库的函数。这样,就可以在Android应用中执行Curl命令,...

    php5.6 curl拓展不能开启资源下载

    php5.6 curl拓展不能开启资源下载 php5.6版的以上方法都不行,是原安装包的.dll文件有问题,下载ssleay32.dll这个文件即可,亲测

    qt5使用curl实现文件下载的示例程序

    - 设置URL:`curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/file.to.download")` - 指定本地保存路径:`curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);` - 定义回调函数,用于接收下载...

    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 ...

    curl-7.53.1_spendrhy_curl_aix7.1安装curl_

    `curl-7.53.1`是该工具的一个特定版本,由`spendrhy`发布,适用于AIX 7.1操作系统。在AIX系统上安装`curl`对于系统管理员和开发人员来说非常重要,因为它提供了对网络资源的便捷访问,特别是用于调试和测试URL。 ...

    curl https://github.com/curl/curl.git

    指的是使用 `curl` 命令行工具从 GitHub 克隆 `curl` 项目的 Git 仓库。`curl` 是一个用于传输数据的命令行工具,它支持多种协议,包括 HTTP、HTTPS、FTP 等。在本例中,它被用来与 Git 协议交互,克隆 `curl/curl` ...

    Qt工程中使用curl进行网络请求,最小程序

    在本文中,我们将深入探讨如何在Qt工程中利用curl库进行网络请求,这是一个最小化的示例,可以帮助开发者了解如何将curl集成到Qt项目中。首先,让我们了解一下curl库和Qt框架的基本概念。 **curl库介绍** curl是一...

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

    curl 命令详解 curl 命令是一种强大的命令行工具,用于传输数据规范的命令行工具,支持包括 HTTP、HTTPS、SCP、SFTP、TFTP 等多种协议。该命令可以用来下载和上传文件、查看 HTTP 头信息、设置 Cookie 和代理服务器...

    cURL(curl-8.4.0)

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

    windows下的CURL上传下载图片

    使用CURL库的`curl_easy_init`函数初始化一个CURL句柄,然后用`curl_easy_setopt`设置各种选项。对于下载操作,关键的选项是`CURLOPT_URL`,用来指定图片的URL,以及`CURLOPT_WRITEFUNCTION`,定义数据接收的回调...

    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-master.zip_curl_curl-master_curlconfig-d

    `curl-master.zip_curl_curl-master_curlconfig-d`这个文件名表明这是一个关于curl源码仓库的压缩包,可能包含了curl的源代码、配置文件以及与`curlconfig-d`相关的文件。 `curl-master`通常指的是curl项目的主分支...

    CUrlHttp封装curl类

    curl库是一个强大的URL传输库,广泛应用于各种网络请求任务,包括文件上传下载、网页抓取、OAuth认证等。CUrlHttp类的出现是为了简化curl的使用,使得开发者无需直接与curl库的底层API打交道,而是通过面向对象的...

    CURL在win和linux下详细教程

    - `-A` 或 `--user-agent` 选项允许你指定一个用户代理字符串,模拟不同浏览器访问,例如 `curl -A "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" -x 123.45.67.89:1080 -o page....

Global site tag (gtag.js) - Google Analytics