我已经尝试了两天以上,无法通过文件上传生成缩略图。我的代码如下:
HTML
<form class="navbar-form pull-left" action="fileupload.php" name="fileupload" method="post" enctype="multipart/form-data">
<label for="file" style="cursor: pointer;padding:5px 0 0 0;font-weight:normal" title="Add Images">IMAGES</label>
<input type="file" name="file[]" multiple id="file"><br>
</form>
PHP
session_start();
$database = $_SESSION['folder'];
$match = $_SESSION['matchLst'];
$tardir = "/var/www/html/projects/" . $database . "/" . $match . "/";
$thumb = $match . "_thumb/";
#$thumbdir = $tardir . $thumb;
$thumbdir = "/var/www/html/projects/images/Match1/Match1_thumb/";
function generateThumbnail($img, $width, $height, $quality = 90)
{
if (is_file($img)) {
$imagick = new Imagick(realpath($img));
$imagick->setImageFormat('jpeg');
$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality($quality);
$imagick->thumbnailImage($width, $height, false, false);
$filename_no_ext = basename($img);
if (file_put_contents($filename_no_ext, $imagick) === false) {
throw new Exception("Could not put contents.");
}
return true;
}
else {
throw new Exception("No valid image provided with {$img}.");
}
}
if(!isset($_FILES['file'])){die();}
if(isset($_FILES['file'])) {
if($_FILES['file']['name']) {
$filename = $_FILES['file']['name'];
$source = $_FILES['file']['tmp_name'];
$target = $tardir . $filename;
$thumb = $thumbdir;
move_uploaded_file(generateThumbnail($source, 100,100,65), $thumb);
}
}
上面的php代码返回以下错误:
HP Fatal error: Uncaught exception 'Exception' with message 'Could not put contents.' in /var/www/html/fileupload.php:23\nStack trace:\n#0 /var/www/html/fileupload.php(41): generateThumbnail('/tmp/phpdFkrX4', 100, 100, 65)\n#1 {main}\n thrown in /var/www/html/fileupload.php on line 23, referer: http://localhost/index.php
当我按照此example中给出的方式对图像路径进行硬编码时,它会起作用。
类似地,当我只想上传选定的图像并更改
move_uploaded_file(generateThumbnail($source, 100,100,65), $thumb);
到
move_uploaded_file($source, $thumb);
相同的代码将图像发布到所需的文件夹。