我有一个现有的图像上传脚本(如下),它工作正常,但我想为其添加一个裁剪功能,因此每张上传的照片都保持正确的纵横比,但被裁剪为 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);
有人可以帮我把这两个放在一起吗?
谢谢