Imagecopyresampled自动裁剪图像

时间:2010-07-21 06:26:02

标签: php image-resizing

我正在使用imagecopyresampled根据特定的宽度和高度创建缩略图。我遇到的问题是他们的身高被压扁了。我想要的是所有缩略图图像都是140x84,如果它们的宽高比不匹配,图像的顶部和底部额外部分会被裁剪为中心。

以下是我到目前为止所提出的任何想法都会受到高度赞赏。

// Create Thumbnail

        $imgsize = getimagesize($targetFile);
    switch(strtolower(substr($targetFile, -3))){
        case "jpg":
            $image = imagecreatefromjpeg($targetFile);    
        break;
        case "png":
            $image = imagecreatefrompng($targetFile);
        break;
        case "gif":
            $image = imagecreatefromgif($targetFile);
        break;
        default:
            exit;
        break;
    }

    $width = 140; //New width of image    
    $height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions

    $x_mid = $width/2;  //horizontal middle
    $y_mid = $height/2; //vertical middle

    $src_w = $imgsize[0];
    $src_h = $imgsize[1];


    $picture = imagecreatetruecolor($width, $height);
    imagealphablending($picture, false);
    imagesavealpha($picture, true);
    $bool = imagecopyresampled($picture, $image, 0, 0, 0, ($y_mid-(84/2)), $width, $height, $src_w, $src_h); 

    if($bool){
        switch(strtolower(substr($targetFile, -3))){
            case "jpg":
                header("Content-Type: image/jpeg");
                $bool2 = imagejpeg($picture,$file_dir."/thumbs/".$imageName,85);
            break;
            case "png":
                header("Content-Type: image/png");
                imagepng($picture,$file_dir."/thumbs/".$imageName);
            break;
            case "gif":
                header("Content-Type: image/gif");
                imagegif($picture,$file_dir."/thumbs/".$imageName);
            break;
        }
    }


    imagedestroy($picture);
    imagedestroy($image);

1 个答案:

答案 0 :(得分:0)

如果要根据图像的高度或宽度重新调整图像大小,则需要先确定。您通常会根据原始图像是纵向还是横向以及所需图像尺寸的方向来解决此问题。然后,您需要根据自己的选择以编程方式计算出其他边缘。

完成后,您可以在(0,0)处对原始图像进行简单的重新取样,并且可以截断悬垂的图像数据。

相关问题