如何解决php脚本创建的截断图像


How to solve truncated images created by php script?

我有一个被php脚本分割的图像。我这样称呼它。

 <img src="/index.php/image-name.jpg">

如果图像超过5分钟,我的脚本将从数据提供程序检索图像的新副本,然后显示新图像。

当提供图像的网站加载了图像,并且这个脚本去获取新的副本时,它通常只显示图像的顶部。Firebug会告诉我图像已损坏或被截断。如果我在一个新的选项卡中打开图像,我的服务器就会有一个完整的副本。如果我在5分钟内再次运行该脚本,它将完美运行。

看起来,如果需要超过一定的时间才能获得图像,它就会失败,只显示顶部。有没有想过如何让它在放弃之前等待更长的时间?或者,也许我完全走错了路。

<?php
  // get the image name from the uri
  $path= $_SERVER['REQUEST_URI'];
  $image = explode("/", $path);
  $image=$image[3];//Get the file name
  $image=str_replace('%20',' ', $image); //make it all spaces
  $localimage='./road_images/'.$image; //where to find the image on the sever
  // check if the image exists, this prevents some kinds of attacks
  if (is_file($localimage)) {
    $age = filemtime($localimage);     // get the file age
    if ($age < time() - (60*5)) { // 5 mins old
        $simage='http://www.someplace/cams/'.$image;
        $simage=str_replace(' ', '%20', $simage);//need to remove the spaces for URLs
        copy($simage, $localimage);
    }
    // serve the image to the user.
    $fp = fopen($localimage, 'r');
    // send the right headers
    header("Content-Type: image/jpg");
    header("Content-Length: " . filesize($localimage));
    // dump the picture and stop the script
    fpassthru($fp);
    exit();
  }
  else
  {
        echo("Error, no such file: '$image'");
  }
?>

编辑:通过编辑发现

        header("Content-Length: " . filesize($localimage));

它按预期工作。还在想原因。

那太痛苦了。我传递了错误的Content-Length标头值。编辑掉内容长度解决了这个问题,所以效果很好。考虑到这是静态内容,我不知道为什么我上面的内容不起作用。

随着更多的研究找到了一种可行的方法。

我把ob_start()放在了起点附近。新的Content-Length标头header('Content-Length: ' . ob_get_length());位于底部,就在脚本退出之前。

这样做,它每次都能工作,对浏览器来说很好。