所以我让这个 PHP 脚本从中心缩放并裁剪成一个正方形;
<?PHP
//resize and crop image by center
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 7;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 80;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width){
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
}else{
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if($dst_img)imagedestroy($dst_img);
if($src_img)imagedestroy($src_img);
}
//usage example
resize_crop_image(100, 100, "test.jpg", "test.jpg");p_image(100, 100, "test.jpg", "test.jpg");
?>
您可以简单地调用以下函数:
resize_crop_image(100, 100, "test.jpg", "test.jpg");p_image(100, 100, "test.jpg", "test.jpg");
添加到JSFiddle的是我的HTML5/JQuery预览文件,然后上传到服务器。
1). 运行此脚本之前,是否需要将镜像上传到服务器?
2). 如果需要事先上传,我如何使用我的表单上传到临时位置,完成工作并移动到特定的目录并删除临时目录?
1)是的,在编辑/裁剪之前,需要在服务器上提供图像的副本。 2)上传的文件会自动存储在临时目录中(它们通常会被复制出来以使用图像,但不必如此)。代码可以从 temp 目录中将它们读取为图像,PHP 也会在脚本末尾自动清理文件。
上传文件时,$_FILES
数组中有一个带有 tmp 名称的键。您可以将其作为源文件传递到函数中,它应该可以毫无问题地与imagecopyresampled
一起使用。临时名称将类似于 $_FILES['nameFromFileFieldOnForm']['tmp_name']
.
如果您的源文件或目标文件是
$source_file = www.example.com/storage/packages/image.jpg
将其更改为
$source_file = ./storage/packages/image.jpg
它在 laravel 5 中对我有用