如何在 php 中正确旋转图像


How to rotate an image properly in php?

我正在使用imagerotate()函数将下面的图像旋转到30度角。

http://postimage.org/image/b7w6dacel/

问题是,每当我旋转图像并将其保存到新路径时,在新路径中图像都会旋转,但周围有黑色,如下所示。

http://postimage.org/image/n3n1vtr9p/8501961e/

原始图像为 450 * 340,旋转后,图像变为 560 * 520。有谁知道我做错了什么。看看下面的源代码。谢谢。

$filename =  "static''". $sessionid . "-1.jpg";
$file= $sessionid . "-1.jpg";
$ir = imagecreatefromjpeg($filename);
$degrees = 30;
$flip=imagerotate($ir, $degrees, 0);
$rotated=imagejpeg($flip, 'c:''xampp''htdocs'''. $file);

根据您旋转的程度,新图像将大于原始图像。您必须缩放或裁剪新图像。此代码将$oldImage扩展到 $newWidth$newHeigth

$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($oldImage), imagesy($oldImage));

希望这有帮助。