PHP - 图像不会在首页加载时显示,但会在第二页加载时显示

时间:2015-06-09 17:01:58

标签: php html

我正在编写一个基于PHP的图像查看器,而且我遇到了一个奇怪的问题。当我单击图像进行查看时,代码表示它应该显示已经创建并保存到硬盘驱动器的图片的已调整大小的版本(因此它不需要多次重新映射图像) 。但是,它只是显示一个损坏的图像并输出一个错误,抱怨它所寻找的文件不存在。如果我刷新页面,文件确实存在,并加载正常。这里发生了什么?我的印象是PHP是单线程的

以下是image-view.php的全部内容(我已经删除了此代码,因为我已将其用于工作,并且与我遇到的问题无关)

以下是resize_image()

中的functions.php函数
//Return the path to a new or already existing resized version of the image you are looking for.
//I repeat: THIS FUNCTION RETURNS A PATH. IT DOES NOT RETURN AN ACTUAL IMAGE.
function resize_image($img, $imgPath, $width) {
    //error_log("!!!Calling resize_image({$img},{$imgName},{$width},{$imgDir})!!!");
    //Put the image in the .cache subdirectory.
    $imgName = end(explode("/",$imgPath));
    $imgDir = str_replace($imgName,"",$imgPath);
    $pathToThumbs = $imgDir . "/.cache/";
    $thumbWidth = $width;
    $thumbHeight = floor(imagesy($img) * ($width / imagesx($img)));
    $thumbName = get_resized_image_name($thumbWidth, $thumbHeight, $imgName);
    $resizedPath = "{$pathToThumbs}{$thumbName}";
    //Don't make a new image if it already exists.
    if (file_exists($pathToThumbs)) {
        if (file_exists($resizedPath)) {
            error_log("Resized image {$resizedPath} already exists. Exiting.");
            return $resizedPath;
        }
    }
    else {
        error_log("Cache folder does not exist. Creating.");
        $old_umask = umask(0);
        mkdir($pathToThumbs, 0777);
        umask($old_umask);
    }
    error_log("Resized image {$resizedPath} does not exist. Creating.");

    $thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
    //This is the magic line right here. Create the thumbnail.
    imagecopyresized($thumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, imagesx($img), imagesy($img));
    if (!file_exists($pathToThumbs)) {

    }
    imagepng($thumb, "{$pathToThumbs}{$thumbWidth}x{$thumbHeight}-{$imgName}");
    return $thumb;
}

3 个答案:

答案 0 :(得分:2)

变化:

imagepng($thumb, "{$pathToThumbs}{$thumbWidth}x{$thumbHeight}-{$imgName}");
return $thumb;

要:

$outPath = "{$pathToThumbs}{$thumbWidth}x{$thumbHeight}-{$imgName}";
imagepng($thumb, $outPath);
return $outPath;

答案 1 :(得分:1)

首次运行时,会将您传入的resource返回imagepng功能。第二次运行时,返回路径。

imagepng($thumb, "{$pathToThumbs}{$thumbWidth}x{$thumbHeight}-{$imgName}");
// $thumb is a resource.
return $thumb;

使函数在两种情况下都返回路径。

答案 2 :(得分:1)

它不起作用的原因是因为在第一次通话时您将返回由$thumb来电返回的imagecreatetruecolor()

问题是它返回图像标识符,而不是文件名。查看documentation

您可以通过更改最后一行

轻松修复代码
//return $thumb;
return $resizedPath;
相关问题