调整图像大小以获得缩略图

resizing an image to get a thumbnail

我正在尝试创建图像的缩略图。我从 php.net 网站获得了 php 代码,但是 returns 这个错误:

Warning: imagejpeg(/Users/michelebrizzi/Sites/htdocs/blogmichele/immagini/ragazza_thumb.jpg): failed to open stream: Permission denied in /Users/michelebrizzi/Sites/htdocs/blogmichele/prova/imagescale.php on line 19

我做错了什么?

这是我用过的 php 代码:

<?php
// File and new size
$filename = $_SERVER['DOCUMENT_ROOT'].'/cartella_sito/immagini/image.jpg';
$percent = 0.5;

// Content type
// header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb, $_SERVER['DOCUMENT_ROOT']."/cartella_sito/immagini/image_thumb.jpg", 75);
?>

再次阅读错误信息。错误消息本身表示权限被拒绝。

这很正常 - 权限被拒绝。检查 unix 级别的文件权限并确保运行 PHP 的用户具有读取权限。 只是为了测试 chmod 到 777。然后恢复到更严格的设置。确保可以访问整个路径链。

也可能是 PHP 没有进入该目录的 directive/permission。我忘记了设置。但是有这件事;对于 htdocs/webroot 之外的目录,您需要明确允许。看到这个 - Make XAMPP/Apache serve file outside of htdocs。但是这似乎不适用,因为您正试图访问 htdocs 中的文件。

尝试将一些错误处理放入:

根据我的经验,有两种方法无法解决这个问题

1) 文件不存在

<?php
// File and new size
$filename = $_SERVER['DOCUMENT_ROOT'].'/cartella_sito/immagini/image.jpg';

if(!file_exists($filename)) {
die("The file does not exist");
}
$percent = 0.5;

// Content type
// header('Content-Type: image/jpeg');

  // Get new sizes
  list($width, $height) = getimagesize($filename);
  $newwidth = $width * $percent;
  $newheight = $height * $percent;

  // Load
  $thumb = imagecreatetruecolor($newwidth, $newheight);
  $source = imagecreatefromjpeg($filename);

  // Resize
  imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight,  $width, $height);

// Output
imagejpeg($thumb, $_SERVER['DOCUMENT_ROOT']."/cartella_sito/immagini/image_thumb.jpg", 75);
?>

2) 您没有正确的权限

假设您使用的是 FileZilla 等客户端,请右键单击图像文件夹并确保您至少具有对该文件的读取权限(通过转到文件夹权限)