使用 php imagejpeg 创建缩略图 - 出现错误 "failed to open stream: Permission denied"

create thumbnail with php imagejpeg - getting error "failed to open stream: Permission denied"

我正在尝试使用 this 功能为之前上传的图片创建缩略图。

原始图片已上传至 mysite/used_uploads,缩略图应在 mysite/used_uploads_thb 创建。

原图上传后直接触发缩略图功能

我也修改了目录的权限,如下,但是问题依旧

chmod("used_uploads_thb", 0777);

目录如下:

mysite/used_uploads

mysite/used_uploads_thb

这是整个脚本。最后一步是给出上述错误。

<?php
$src = substr($filePath, 1);

//$src example: used_uploads/252-558ec2e5dc45c-alfa-romeo-giulia - 2.jpg
chmod("used_uploads_thb", 0777);

$dest = '/used_uploads_thb';
$desired_width="100";

function make_thumb($src, $dest, $desired_width) {

/* read the source image */    
    $source_image = imagecreatefromjpeg($src);

$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width  */
$desired_height = floor($height * ($desired_width / $width));

/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);

/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);
                  print_r(error_get_last());              
}

make_thumb($src, $dest, $desired_width);
?>

这是错误信息:

Array
(
[type] => 2
[message] => imagejpeg(/used_uploads_thb): failed to open stream:    Permission denied
[file] => /Applications/MAMP/htdocs/SiteCar/used_thumbnail.php
[line] => 26
)

感谢您的帮助。

确保你的两个目录权限都设置为 0777 或者你的源图像文件名从不使用 space 如果你在 linux 上工作,因为你需要添加 [=16= 的转义字符] '\ ' 在文件名中的每个 space 上,确保在上传后将其重命名为

$src = md5('252-558ec2e5dc45c-alfa-romeo-giulia - 2.jpg') 。 '.jpg';

仅作记录。

问题出在缩略图的目标路径上。我的原始代码只有目录。我错误地假设名称与原始文件相同并且会自动创建。不是这样。

这是工作代码: preg_replace 存在只是因为我将缩略图放在原始图像的单独目录中。

<?php
$src = $new_name = $filePath;
$new_name = preg_replace('/used_uploads\/(.*)$/', '', $new_name);
$src = $_SERVER['DOCUMENT_ROOT'] . $src;
$dest = 'used_uploads_thb'. $new_name;
$desired_width="100";


function make_thumb($src, $dest, $desired_width) {

/* read the source image */    
    $source_image = imagecreatefromjpeg($src);

$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width  */
$desired_height = floor($height * ($desired_width / $width));

/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);

/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

/* create the physical thumbnail image to its destination */

imagejpeg($virtual_image,$dest);
    //print_r(error_get_last());
}

 make_thumb($src, $dest, $desired_width);
?>