php等比例截取图片并替换掉原文件

[php] 2024-04-25 圈点793

摘要:imagecopyresampled将指定目录中的图片截取成收缩或者是放大的图,替换原文件。

/*

将指定目录中的图片截取成收缩或者是放大的图,替换原文件。


需要修改参数

$file_path     相对系统的绝对路径目录

$file_names 取文件

$new_width = 560;   截取图的宽

$new_height = 260;  截取图的高


*/


$file_path = "E:/images/a/";

$file_names = glob("{$file_path}*.jpg");


foreach ($file_names as $filename) {

if (file_exists($filename)) {

//$a = basename($filename); 

//$file_end = explode('.', $a);

//$filenameok = "{$file_path}{$file_end[0]}_big.{$file_end[1]}";

// Content type

header('Content-Type: image/jpeg');

// Get new dimensions

list($width, $height) = getimagesize($filename);

$new_width = 560;

$new_height = 260;

//宽高比

if($new_width/$new_height > $width/$height){

$height_qu = $new_height / $new_width * $width;

$height_up = ($height - $height_qu)/2;

$image_p = imagecreatetruecolor($new_width, $new_height);

$image = imagecreatefromjpeg($filename);

imagecopyresampled($image_p, $image, 0, 0, 0, $height_up, $new_width, $new_height, $width, $height_qu);

// Output

if(!imagejpeg($image_p, $filename, 100)){

exit(0);

}

}else{

$width_qu = $new_width / $new_height * $height;

$width_lf = ($width - $width_qu)/2;

$image_p = imagecreatetruecolor($new_width, $new_height);

$image = imagecreatefromjpeg($filename);

imagecopyresampled($image_p, $image, 0, 0, $width_lf, 0, $new_width, $new_height, $width_qu, $height);

// Output

if(!imagejpeg($image_p, $filename, 100)){

exit(0);

}

}

}else{

//echo "dot exist";

}

}


exit();

php  截图  

感谢反馈,已提交成功,审核后即会显示