我正在使用 PHP 旋转和裁剪图像,但显示黑色边框,我知道您可以更改背景颜色,但我想旋转和裁剪图像以填充整个图像。基本上类似于background-size: cover;
CSS 中的(左)与background-size: contain;
(右)。
看下图,右边是我现在得到的,左边是我想要实现的。旋转的度数是动态的,要生成的图像和源图像都是正方形 (200x200)。
编辑:这是我快速而肮脏的代码:
$rotate = imagecreatefromjpeg($image);
// part of code created by www.thewebhelp.com, modified
$square_size = 200;
$original_width = imagesx($rotate);
$original_height = imagesy($rotate);
if($original_width > $original_height){
$new_height = $square_size;
$new_width = $new_height*($original_width/$original_height);
}
if($original_height > $original_width){
$new_width = $square_size;
$new_height = $new_width*($original_height/$original_width);
}
if($original_height == $original_width){
$new_width = $square_size;
$new_height = $square_size;
}
$new_width = round($new_width);
$new_height = round($new_height);
$smaller_image = imagecreatetruecolor($new_width, $new_height);
$square_image = imagecreatetruecolor($square_size, $square_size);
imagecopyresampled($smaller_image, $rotate, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);
if($new_width>$new_height){
$difference = $new_width-$new_height;
$half_difference = round($difference/2);
imagecopyresampled($square_image, $smaller_image, 0-$half_difference+1, 0, 0, 0, $square_size+$difference, $square_size, $new_width, $new_height);
}
if($new_height>$new_width){
$difference = $new_height-$new_width;
$half_difference = round($difference/2);
imagecopyresampled($square_image, $smaller_image, 0, 0-$half_difference+1, 0, 0, $square_size, $square_size+$difference, $new_width, $new_height);
}
if($new_height == $new_width){
imagecopyresampled($square_image, $smaller_image, 0, 0, 0, 0, $square_size, $square_size, $new_width, $new_height);
}
$degrees = rand(1,360);
$square_image = imagerotate($square_image, $degrees, 0);
imagejpeg($square_image,NULL,100);