在php中上载时,将图像大小调整为相同的宽度和高度
我正在尝试使用此功能在上载时自动调整图像大小:在php中上载时,将图像大小调整为相同的宽度和高度,php,Php,我正在尝试使用此功能在上载时自动调整图像大小: function ak_img_resize($target, $newcopy, $w, $h, $ext) { list($w_orig, $h_orig) = getimagesize($target); $scale_ratio = $w_orig / $h_orig; if (($w / $h) > $scale_ratio) { $w = $h * $scale_ratio;
function ak_img_resize($target, $newcopy, $w, $h, $ext) {
list($w_orig, $h_orig) = getimagesize($target);
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio) {
$w = $h * $scale_ratio;
} else {
$h = $w / $scale_ratio;
}
$img = "";
$ext = strtolower($ext);
if ($ext == "gif"){
$img = imagecreatefromgif($target);
} else if($ext =="png"){
$img = imagecreatefrompng($target);
} else {
$img = imagecreatefromjpeg($target);
}
$tci = imagecreatetruecolor($w, $h);
// imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
imagejpeg($tci, $newcopy, 80);
}
然后:
$target_file = "img/".$admit_roll.".".$ext;
$resized_file = "img/".$admit_roll.".".$ext;
$wmax = 200;
$hmax = 200;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $ext);
但即使
$wmax
abd$hmax
相同,也不会返回正方形大小的图像。如何使其返回正方形大小的图像?您可以使用函数imagecopyresized()
调整其大小:
函数img\u resize($target、$newcopy、$w、$h、$ext){
列表($w_orig,$h_orig)=getimagesize($target);
$img=“”;
$ext=strtolower($ext);
如果($ext==“gif”){
$img=imagecreatefromformgif($target);
}else if($ext==“png”){
$img=imagecreatefrompng($target);
}否则{
$img=imagecreatefromjpeg($target);
}
$tci=ImageCreateTureColor($w,$h);
imagecopyresized($tci、$img、0、0、0、0、0、$w、$h、$w原始值、$h\U orig);
imagejpeg($tci,$newcopy);
}
有了这个函数,你就不必关心纵横比了,它会为你做的
编辑:您可以将函数
imagecopyresized()
替换为imagecopyresampled()
,它将执行相同的操作,虽然质量更高,但使用更多的cpu时间图像处理非常复杂。你可以自己学习,这很有趣,有时也很有用。但这也很乏味,因为你需要了解其他人已经解决的所有问题
另一种选择是使用其中一种方法,使您能够轻松实现这一点
例如:
看一看,这是多么的容易
// open file a image resource
$img = Image::make('public/foo.jpg');
// crop the best fitting 5:3 (600x360) ratio and resize to 600x360 pixel
$img->fit(600, 360);
// crop the best fitting 1:1 ratio (200x200) and resize to 200x200 pixel
$img->fit(200);
// add callback functionality to retain maximal original image size
$img->fit(800, 600, function ($constraint) {
$constraint->upsize();
});