gpt4 book ai didi

php - 调整大小然后裁剪 PHP

转载 作者:可可西里 更新时间:2023-11-01 00:37:17 25 4
gpt4 key购买 nike

好的,基本上我希望所有图像都是 170x170 像素的正方形。因此,如果图像不是正方形,我希望调整它的大小,然后在中间裁剪..

我花了很多时间玩这个但我一无所获..我已经让它裁剪了较大图像的一部分等,但我特别需要调整图像大小,然后裁剪..

如有任何帮助,我们将不胜感激。

// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];

if($sw > $sh) // Horizontal Rectangle?
{
$newwidth = ($sw/$sh)*170;
$newheight=170;
$x_pos = ($sw - $sh) / 2;
$x_pos = ceil($x_pos);
$y_pos=0;
}

else if($sh > $sw) // Vertical Rectangle?
{
$newheight = ($sh/$sw)*170;
$newwidth=170;
$y_pos = ($sh - $sw) / 2;
$y_pos = ceil($y_pos);
$x_pos=0;
}
else //Already Square
{
$newheight=170;
$newwidth=170;
}

$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF

if (!$im) {
// We get errors from PHP's ImageCreate functions...
// So let's echo back the contents of the actual image.
readfile ($img);
} else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor (170, 170);
// Copy from image source, resize it, and paste to image destination
imagecopyresampled($thumb, $im, 0, 0, 180, $y_pos, 170, 170, $newwidth,
$newheight);
}

最佳答案

好的,这是一个可以工作的;

<?
$img = 'leaf.jpg';
// get image size of img
$x = @getimagesize($img);

// image dimensions
$sw = $x[0];
$sh = $x[1];

//dest size
$dSize = 170;

//find smallerst part and get needed scale and offset
$yOff = 0;
$xOff = 0;
if($sw < $sh) {
$scale = $dSize / $sw;
$yOff = $sh/2 - $dSize/$scale/2;
} else {
$scale = $dSize / $sh;
$xOff = $sw/2 - $dSize/$scale/2;
}

$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF

if (!$im) {
// We get errors from PHP's ImageCreate functions...
// So let's echo back the contents of the actual image.
readfile ($img);
} else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor ($dSize,$dSize);
// Copy from image source, resize it, and paste to image destination
imagecopyresampled($thumb, $im,
0, 0,
$xOff,$yOff,
$dSize, $dSize,
$dSize / $scale ,$dSize / $scale);
}
header('content-type:image/jpeg');
imagejpeg($thumb);
//imagejpeg($im);

关于php - 调整大小然后裁剪 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4443320/

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