ImageCapture.class.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /**
  3. * 下载远程图片
  4. * @param string $url 图片的绝对url
  5. * @param string $filepath 文件的完整路径(包括目录,不包括后缀名,例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名
  6. * @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false
  7. */
  8. class ImageCapture {
  9. private static function init ( $url ) {
  10. $curl = curl_init( $url );
  11. curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
  12. curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
  13. curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
  14. curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
  15. // 尝试连接时间 10s
  16. curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 10 * 1000 );
  17. curl_setopt( $curl, CURLOPT_MAXREDIRS, 5 );
  18. curl_setopt( $curl, CURLOPT_TIMEOUT, 30 );
  19. return $curl;
  20. }
  21. public static function capture ( $url ) {
  22. $mime = array(
  23. '.jpg' => 'image/jpeg',
  24. '.png' => 'image/png',
  25. '.gif' => 'image/gif',
  26. '.bmp' => 'image/bmp'
  27. );
  28. $curl = self::init( $url );
  29. $result = curl_exec( $curl );
  30. if ( curl_errno( $curl ) ) {
  31. curl_close( $curl );
  32. return null;
  33. }
  34. $info = curl_getinfo( $curl );
  35. curl_close( $curl );
  36. if ( $result === false ) {
  37. return null;
  38. }
  39. if ( $info[ 'http_code' ] != 200 ) {
  40. return null;
  41. }
  42. $suffix = self::getSuffix( $info );
  43. $filepath = tempnam( sys_get_temp_dir(), '' );
  44. $file = fopen( $filepath, 'wb' );
  45. if ( fwrite( $file, $result ) === false ) {
  46. fclose( $file );
  47. return null;
  48. }
  49. fclose( $file );
  50. return array (
  51. 'filepath' => $filepath,
  52. 'suffix' => $suffix,
  53. 'mime' => $mime[ $suffix ]
  54. );
  55. }
  56. /**
  57. * 根据给定的HTTP信息获取图片的后缀
  58. * @param $info HTTP信息
  59. * @return 找到的后缀名
  60. */
  61. private static function getSuffix ( &$info ) {
  62. $contentType = $info[ 'content_type' ];
  63. $suf = array();
  64. if ( !empty( $contentType ) && preg_match( '/(jpg|png|jpeg|gif|bmp)/i', $contentType, $suf ) === 1 ) {
  65. return "." . str_replace( "jpeg", "jpg", strtolower( $suf[ 0 ] ) );
  66. }
  67. if ( preg_match( '/(jpg|png|jpeg|gif|bmp)/i', $info[ 'url' ], $suf ) === 1 ) {
  68. return "." . str_replace( "jpeg", "jpg", strtolower( $suf[ 0 ] ) );
  69. }
  70. return ".jpg";
  71. }
  72. }