php中使用gd库实现远程图片下载实例

因为今天想写个远程下载图片的类,提前热身写了个php gd库实现远程图片下载功能,当然curl实现更好,php gd库实现远程图片下载功能主要使用gd库的两个函数ImageCreateFromXXX()用于生成图片函数和ImageXXX函数,XXX表示不同图片的扩展名,所以你要想办法获取远程图片的扩展名了,附上php代码如下:

  1. <?php
  2. header("Content-type:text/html ; charset=utf-8");
  3. if (!emptyempty($_POST['submit'])){
  4. $url = $_POST['url'];
  5. $pictureName = $_POST['pictureName'];
  6. $img = getPicture($url,$pictureName);
  7. echo '<pre><img src="'.$img.'"></pre>';
  8. }
  9. function getPicture($url,$pictureName){
  10. if ($url == "") return false;
  11. //获取图片的扩展名
  12. $info = getimagesize($url);
  13. $mime = $info['mime'];
  14. $type = substr(strrchr($mime,'/'), 1);
  15. //不同的图片类型选择不同的图片生成和保存函数
  16. switch($type){
  17. case 'jpeg':
  18. $img_create_func = 'imagecreatefromjpeg';
  19. $img_save_func = 'imagejpeg';
  20. $new_img_ext = 'jpg';
  21. break;
  22. case 'png':
  23. $img_create_func = 'imagecreatefrompng';
  24. $img_save_func = 'imagepng';
  25. $new_img_ext = 'png';
  26. break;
  27. case 'bmp':
  28. $img_create_func = 'imagecreatefrombmp';
  29. $img_save_func = 'imagebmp';
  30. $new_img_ext = 'bmp';
  31. break;
  32. case 'gif':
  33. $img_create_func = 'imagecreatefromgif';
  34. $img_save_func = 'imagegif';
  35. $new_img_ext = 'gif';
  36. break;
  37. case 'vnd.wap.wbmp':
  38. $img_create_func = 'imagecreatefromwbmp';
  39. $img_save_func = 'imagewbmp';
  40. $new_img_ext = 'bmp';
  41. break;
  42. case 'xbm':
  43. $img_create_func = 'imagecreatefromxbm';
  44. $img_save_func = 'imagexbm';
  45. $new_img_ext = 'xbm';
  46. break;
  47. default:
  48. $img_create_func = 'imagecreatefromjpeg';
  49. $img_save_func = 'imagejpeg';
  50. $new_img_ext = 'jpg';
  51. }
  52. if ($pictureName == ""){
  53. $pictureName = time().".{$new_img_ext}";
  54. }else{
  55. $pictureName = $pictureName.".{$new_img_ext}";
  56. }
  57. $src_im = $img_create_func($url); //由url创建新图片
  58. $img_save_func($src_im, $pictureName); //输出文件到文件
  59. return $pictureName;
  60. }
  61. ?>
  62. <form method="POST" action="">
  63. 远程url地址:<input type="text" name="url" size=20 /><br />
  64. 文件名称:<input type="text" name="pictureName" size=20 />
  65. <input type="submit" name="submit" value="下载" />
  66. </form>