【问题标题】:Create Thumbnail according to aspect ratio of image while Upload Image with php在使用php上传图像时根据图像的纵横比创建缩略图
【发布时间】:2017-11-13 08:51:21
【问题描述】:

我想在上传图片时创建缩略图,我已经创建了上传脚本。

<?php
if (isset($_POST['upload'])) {
$target = "./img/".basename($_FILES['image']['name']);

$image = $_FILES['image']['name'];

$sql = "INSERT INTO `image`(`image`) VALUES ('$image')";
mysqli_query($connection, $sql);

if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$smsg = "Image Uploaded Successfuly";
}else {
$fmsg = "An Error Occure During Upload";
}

}
?>

并调整图像大小:

function resize($newHeight, $targetFile, $originalFile) {

$info = getimagesize($originalFile);
$mime = $info['mime'];

switch ($mime) {
        case 'image/jpeg':
                $image_create_func = 'imagecreatefromjpeg';
                $image_save_func = 'imagejpeg';
                $new_image_ext = 'jpg';
                break;

        case 'image/png':
                $image_create_func = 'imagecreatefrompng';
                $image_save_func = 'imagepng';
                $new_image_ext = 'png';
                break;

        case 'image/gif':
                $image_create_func = 'imagecreatefromgif';
                $image_save_func = 'imagegif';
                $new_image_ext = 'gif';
                break;

        default: 
                throw new Exception('Unknown image type.');
}

$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);

$newWidth = ($width / $height) * $newHeight;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

if (file_exists($targetFile)) {
        unlink($targetFile);
}
$image_save_func($tmp, "thumb/$targetFile.$new_image_ext");
}

我像这样加入两个脚本

<?php
if (isset($_POST['upload'])) {
$target = "./img/".basename($_FILES['image']['name']);

$image = $_FILES['image']['name'];

$sql = "INSERT INTO `image`(`image`) VALUES ('$image')";
mysqli_query($connection, $sql);

if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$smsg = "Image Uploaded Successfuly";

resize(320, '$target', '$target');     //resize function
}else {
$fmsg = "An Error Occure During Upload";
}

}
?>

当我尝试加入这两个脚本时,图像上传但未创建缩略图错误 = 没有这样的文件或目录。

任何人都可以帮助我在上传图像时加入这两个脚本并创建缩略图。

【问题讨论】:

    标签: php image thumbnails aspect-ratio


    【解决方案1】:

    下一行变量中的单引号没有被解析,这些值实际上被解释为$target而不是预期的folder/filename.xxx

    resize(320, '$target', '$target');
    

    要么删除它们:

    resize(320, $target, $target);
    

    或使用双引号。

    resize(320, "$target", "$target");
    

    在字符串方面咨询http://php.net/manual/en/language.types.string.php

    使用 PHP 的错误报告并确保路径正确,并且文件夹是可写且具有适当权限的。

    【讨论】:

    • dv'er(刚才)可以分享他们对此的看法吗?那会有所帮助。否则,不需要 dv;这个答案没有错。
    猜你喜欢
    • 2012-07-25
    • 2014-06-02
    • 1970-01-01
    • 2012-09-21
    • 2013-06-08
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多