gpt4 book ai didi

php - 从中心裁剪并在 PHP 中调整大小(函数)

转载 作者:行者123 更新时间:2023-12-05 01:03:14 26 4
gpt4 key购买 nike

我想要一个功能,可以在不丢失纵横比的情况下调整图像的特定高度和重量。所以首先我想裁剪它然后调整它的大小。

这是我目前得到的:

function image_resize($src, $dst, $width, $height, $crop=1){

if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";

$type = strtolower(substr(strrchr($src,"."),1));
if($type == 'jpeg') $type = 'jpg';
switch($type){
case 'bmp': $img = imagecreatefromwbmp($src); break;
case 'gif': $img = imagecreatefromgif($src); break;
case 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported picture type!";
}

// resize
$originalW = $w;
$originalH = $h;

if($crop){
if($w < $width or $h < $height) return "Picture is too small!";
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width and $h < $height) return "Picture is too small!";
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}

$new = imagecreatetruecolor($width, $height);

// preserve transparency
if($type == "gif" or $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}

imagecopyresampled($new, $img, 0, 0, ($originalW - $width)/2, ($originalH - $height)/2, $width, $height, $w, $h);


switch($type){
case 'bmp': imagewbmp($new, $dst); break;
case 'gif': imagegif($new, $dst); break;
case 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}

该功能运行良好。但我还是有问题。例如:当我将 (300 × 450) 的肖像图像调整为 (260 x 140) 时,我得到一个我不想要的黑色边栏。

这是两张图片:

postimage.org/image/6vvq5l5sn enter image description here

最佳答案

它对我有用。你可以试试:

$x=288; $y=202; // my final thumb
$ratio_thumb=$x/$y; // ratio thumb

list($xx, $yy) = getimagesize($image); // original size
$ratio_original=$xx/$yy; // ratio original

if ($ratio_original>=$ratio_thumb) {
$yo=$yy;
$xo=ceil(($yo*$x)/$y);
$xo_ini=ceil(($xx-$xo)/2);
$xy_ini=0;
} else {
$xo=$xx;
$yo=ceil(($xo*$y)/$x);
$xy_ini=ceil(($yy-$yo)/2);
$xo_ini=0;
}

imagecopyresampled($thumb, $source, 0, 0, $xo_ini, $xy_ini, $x, $y, $xo, $yo);

关于php - 从中心裁剪并在 PHP 中调整大小(函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12059387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com