0

我有一个现有的图像上传脚本(如下),它工作正常,但我想为其添加一个裁剪功能,因此每张上传的照片都保持正确的纵横比,但被裁剪为 200 x 200 像素。

我已经查看了与此相关的其他关于 SO 的问题,但理想情况下,我想在我的脚本中添加裁剪,而不是实现一个全新的,如果这有意义的话。

有人可以帮忙吗?

一如既往地感谢。

mkdir("images/$user_id");
$saveto = "images/$user_id/$user_id.jpg";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;

switch($_FILES['image']['type'])
{
    case "image/gif":   $src = imagecreatefromgif($saveto); break;

    case "image/jpeg":  // Both regular and progressive jpegs
    case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;

    case "image/png":   $src = imagecreatefrompng($saveto); break;

    default:            $typeok = FALSE; break;
}

if ($typeok)
{




    list($w, $h) = getimagesize($saveto);
    $max = 200;
    $tw  = $w;
    $th  = $h;

    if ($w > $h && $max < $w)
    {
        $th = $max / $w * $h;
        $tw = $max;
    }
    elseif ($h > $w && $max < $h)
    {
        $tw = $max / $h * $w;
        $th = $max;
    }
    elseif ($max < $w)
    {
        $tw = $th = $max;
    }

    $tmp = imagecreatetruecolor($tw, $th);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
    imageconvolution($tmp, array( // Sharpen image
                            array(-1, -1, -1),
                            array(-1, 16, -1),
                            array(-1, -1, -1)
                           ), 8, 0);
    imagejpeg($tmp, $saveto);
    imagedestroy($tmp);
    imagedestroy($src);


}

编辑:我发现以下脚本在其自己的页面上运行良好,但是我无法在现有的上传脚本中或之后实现它 - 我得到一些“无法打开流:没有这样的文件或目录' 错误 - 但是图像的路径是正确的(我已经确认它是正确的):

$filename = 'images/$user_id/$user_id.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 25;
$top = 25;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);

有人可以帮我把这两个放在一起吗?

谢谢

4

2 回答 2

1

看看:Gregwar/Image

它非常易于使用,而且非常高效。

  • resize($width, $height, $background): 调整图像大小,将保持比例并且从不放大

  • scaleResize($width, $height, $background):调整图像大小,将保留比例

  • forceResize($width, $height, $background): 调整图片大小,将图片强制调整为 $width by $height

  • cropResize($width, $height, $background): 调整图像大小并保留比例并裁剪空白

于 2012-09-16T16:27:42.210 回答
0

感谢大家的回复-我通过更改使我的脚本正常工作

$filename = 'images/$user_id/$user_id.jpg';

$filename = "images/$user_id/$user_id.jpg";
于 2012-09-16T17:04:17.767 回答