Php 在上载到服务器之前或之后裁剪图像
所以我有了这个PHP脚本,可以从中心开始缩放并裁剪成一个正方形Php 在上载到服务器之前或之后裁剪图像,php,Php,所以我有了这个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 =
<?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");
?>
在上传到服务器之前,添加到我的HTML5/JQuery预览文件
1)。在运行此脚本之前,是否需要将图像上载到服务器
2)。如果需要事先上传,我如何使用我的表单上传到临时位置,完成工作并移动到特定目录并删除临时目录?1)是的,您需要在服务器上保存一份图像副本,然后才能对其进行编辑/裁剪。2) 上载的文件会自动存储在临时目录中(它们通常会被复制出来以使用映像,但不必如此)。您的代码可以将它们作为图像从temp目录中读取,PHP也会在脚本结束时自动清理文件
上载文件时,在
$\u FILES
数组中有一个带有tmp名称的键。您只需将其作为源文件传递到函数中,它就可以与imagecopyresampled
一起工作,不会出现任何问题。如果源文件或目标文件为,则临时名称类似于$\u FILES['nameFromFileFieldOnForm']['tmp\u name']
$source_file = www.example.com/storage/packages/image.jpg
换成
$source_file = ./storage/packages/image.jpg
在laravel 5中,它对我很有用。你的意思是说遵循本教程:1)是的,在编辑/裁剪图像之前,需要在服务器上保存一份图像副本。2) 上载的文件会自动存储在临时目录中(它们通常会被复制出来以使用映像,但不必如此)。您的代码可以将它们作为临时目录中的图像读取,PHP也会在脚本末尾自动清理文件。^@JonathanKuhn,第一个问题现在已经清楚了,我的第二个问题似乎大部分已经为我解决了!上载文件时,在
$\u FILES
数组中有一个带有tmp名称的键。您只需将其作为源文件传递到函数中,它就可以与imagecopyresampled一起工作,不会出现任何问题。临时名称类似于$\u FILES['nameFromFileFieldOnForm']['tmp\u name']
。只需将“$mimeType”替换为images mimes类型,并将$image
替换为宽度和高度为$image['width']=40
,$image['height']=20
的数组。。这很简单,试试看。
$source_file = ./storage/packages/image.jpg