温馨提示×

php imagecreatefrompng如何处理图像旋转

PHP
小樊
103
2024-11-29 20:38:00
栏目: 编程语言

在PHP中,使用imagecreatefrompng()函数加载PNG图像后,可以使用imagerotate()函数对图像进行旋转

<?php // 加载PNG图像 $image = imagecreatefrompng('input.png'); // 设置旋转角度(逆时针旋转45度) $angle = 45; // 获取原始图像的宽度和高度 $width = imagesx($image); $height = imagesy($image); // 计算旋转后的新尺寸 $new_width = abs($width * cos($angle * M_PI / 180)) + abs($height * sin($angle * M_PI / 180)); $new_height = abs($width * sin($angle * M_PI / 180)) + abs($height * cos($angle * M_PI / 180)); // 创建一个新的空白图像,用于存放旋转后的图像 $rotated_image = imagecreatetruecolor($new_width, $new_height); // 保持PNG图像的透明度 imagealphablending($rotated_image, false); imagesavealpha($rotated_image, true); // 将原始图像按比例缩放到新尺寸 $ratio_width = $new_width / $width; $ratio_height = $new_height / $height; $ratio = min($ratio_width, $ratio_height); $new_width = $width * $ratio; $new_height = $height * $ratio; $src_x = ($width - $new_width) / 2; $src_y = ($height - $new_height) / 2; imagecopyresampled($rotated_image, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $width, $height); // 输出旋转后的图像 header('Content-type: image/png'); imagepng($rotated_image); // 销毁图像资源 imagedestroy($image); imagedestroy($rotated_image); ?> 

这个示例中,我们首先加载名为input.png的PNG图像,然后设置旋转角度为45度。接下来,我们计算旋转后的新尺寸,并创建一个新的空白图像。我们将原始图像按比例缩放到新尺寸,然后使用imagecopyresampled()函数将原始图像复制到新的空白图像上。最后,我们输出旋转后的图像并销毁图像资源。

0