我有 2个网站 其中 有 一个网站 里面图片 要从另外一个网站获取如果数据库 有图片 就是<img src= "a.jpg">没有 就是<img src= "a.php?id=100"> 由a.php 根据ID 去获取图片我想知道   php 文件 怎么返回一个图片???header("Content-type:image/jpeg");
$img=imagecreatefromjpeg("1290656854-874636.jpg");
imagejpeg($img);
imagedestroy($img);我找了代码 这样是可以的.... 但如果不是jpg 的呢??  应该有更好的代码吧

解决方案 »

  1.   

    header("Content-type:image/jpeg");
    $img=imagecreatefromjpeg("1290656854-874636.jpg");
    imagejpeg($img);
    imagedestroy($img);
    红色部分是可变的,如imagejpeg这个也有imagepng等等,你根据获取的图片而得到相应的格式然后判断用哪个方法
      

  2.   

    除了imagejpeg还有iamgegif,imagepng,可以定义一个$type,根据type值选择相应的函数switch($type)
       {
        case 'png':{
           $img=imagecreatefrompng("1290656854-874636.jpg");
           imagepng($im);
          }  break;
        case 'jpeg':do another thing ;break;
        case 'gif':do another thing;break;
    }    }
      

  3.   

    $t = getimagesize('1290656854-874636.jpg');
    echo $t['mime']; //看看就知道了
      

  4.   

    switch($type)
      {
      case 'png':{
      $img=imagecreatefrompng("1290656854-874636.jpg");
      imagepng($im);
      } break;
      case 'jpeg':do another thing ;break;
      case 'gif':do another thing;break;
    }
      

  5.   

    大概是这样:a.php?id=100a.php
    $id = $_GET['id'];//...$img_file = getImgFromDb($id);//图片路径$type = mime_content_type($img_file);//类型
    switch($type){
       'image/jpeg':
         header("Content-type:image/jpeg");
         $img=imagecreatefromjpeg($img_file);
         imagejpeg($img);
         imagedestroy($img);
         break;
       'image/png':
         header("Content-type:image/png");
         $img=imagecreatefrompng($img_file);
         imagepng($img);
         imagedestroy($img);break;
       'image/gif':
         header("Content-type:image/gif");
         $img=imagecreatefromgif($img_file);
         imagegif($img);
         imagedestroy($img);
    }