我想将我的图像调整为正方形。假设我想要一个 500x500 的平方图像并且我有一个 300x600 的图像我想将该图像的大小调整为 200x500,然后为其添加一个白色背景以使其成为 500x500
通过这样做,我得到了一些很好的效果:
$TargetImage = imagecreatetruecolor(300, 600);
imagecopyresampled(
$TargetImage, $SourceImage,
0, 0,
0, 0,
300, 600,
500, 500
);
$final = imagecreatetruecolor(500, 500);
$bg_color = imagecolorallocate ($final, 255, 255, 255)
imagefill($final, 0, 0, $bg_color);
imagecopyresampled(
$final, $TargetImage,
0, 0,
($x_mid - (500/ 2)), ($y_mid - (500/ 2)),
500, 500,
500, 500
);
Run Code Online (Sandbox Code Playgroud)
它几乎做对了一切。图片居中,一切正常。除了背景是黑色而不是白色:/
有谁知道我做错了什么?
我认为这就是你想要的:
<?php
$square=500;
// Load up the original image
$src = imagecreatefrompng('original.png');
$w = imagesx($src); // image width
$h = imagesy($src); // image height
printf("Orig: %dx%d\n",$w,$h);
// Create output canvas and fill with white
$final = imagecreatetruecolor($square,$square);
$bg_color = imagecolorallocate ($final, 255, 255, 255);
imagefill($final, 0, 0, $bg_color);
// Check if portrait or landscape
if($h>=$w){
// Portrait, i.e. tall image
$newh=$square;
$neww=intval($square*$w/$h);
printf("New: %dx%d\n",$neww,$newh);
// Resize and composite original image onto output canvas
imagecopyresampled(
$final, $src,
intval(($square-$neww)/2),0,
0,0,
$neww, $newh,
$w, $h);
} else {
// Landscape, i.e. wide image
$neww=$square;
$newh=intval($square*$h/$w);
printf("New: %dx%d\n",$neww,$newh);
imagecopyresampled(
$final, $src,
0,intval(($square-$newh)/2),
0,0,
$neww, $newh,
$w, $h);
}
// Write result
imagepng($final,"result.png");
?>
Run Code Online (Sandbox Code Playgroud)
另请注意,如果您想缩小 300x600 以适应 500x500,同时保持纵横比,您将获得 250x500 而不是 200x500。
| 归档时间: |
|
| 查看次数: |
2322 次 |
| 最近记录: |