裁剪逻辑导致黑色图像

时间:2019-09-05 05:04:35

标签: php php-gd

努力使数学正确进行图像裁剪,希望其他人能够看到我的问题。它似乎超出了图像的尺寸,在结果的左侧留下了原始图像的1个像素。

function thumbnail_create($file, $w, $h, $crop = false, $output_filename = null, $output_dirname = null)
{
    list($width, $height) = getimagesize(FILESPATH . $file);
    $r = $width / $height;

    if ($crop) {
        if ($width > $height) {
            $width = ceil($width - ($width * abs($r - $w / $h)));
        } else {
            $height = ceil($height - ($height * abs($r - $w / $h)));
        }

        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w / $h > $r) {
            $newwidth = $h * $r;
            $newheight = $h;
        } else {
            $newheight = $w / $r;
            $newwidth = $w;
        }
    }

    $mime = mime_content_type(FILESPATH . $file);
    $handler = "imagepng";

    if (in_array($mime, ["image/gif"])) {
        $src = imagecreatefromgif(FILESPATH . $file);
        $handler = "imagegif";
    } elseif (in_array($mime, ["image/jpeg", "image/pjpeg", "image/jpeg", "image/pjpeg"])) {
        $src = imagecreatefromjpeg(FILESPATH . $file);
        $handler = "imagejpeg";
    } elseif (in_array($mime, ["image/png"])) {
        $src = imagecreatefrompng(FILESPATH . $file);
    }

    if (!isset($src) || !$src) {
        return false;
    }

    $newImage = imagecreatetruecolor($newwidth, $newheight);
    imagealphablending($newImage, false);
    imagesavealpha($newImage, true);

    imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    if (!empty($output_dirname)) {
        make_dir($output_dirname);
    }

    // BUILD OUTPUT PATH/FILE
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    if (empty($output_filename)) {
        $output_filename = str_replace("." . $ext, '-thumb.' . $ext, basename($file));
    }

    if (empty($output_dirname)) {
        $output_dirname = dirname($file);
    }

    $output = $output_dirname . '/' . $output_filename;
    $handler($newImage, FILESPATH . $output);

    return $output;
}
thumbnail_create('news/feature/fluffy-kitty.png, 100, 100, true)

之前:

enter image description here

之后:

enter image description here

原始宽度:int(862)
原始高度:int(192)
裁剪宽度:浮点型(-2146)
裁剪高度:int(192)

0 个答案:

没有答案