欢迎来到辽宁社交动力网络科技有限公司
建站资讯

当前位置: 首页 > 建站资讯 > 建站教程 > PHP教程

php-gd怎么翻转图片_php-gd水平垂直翻转图像

作者:wap手机网站建站 来源:php教程网站日期:2025-10-12
PHP中GD库翻转图片需手动实现:1. 水平翻转通过创建新图像并从原图右侧逐列复制像素到左侧;2. 垂直翻转则从底部向上逐行复制;3. 对角翻转可组合前两者或遍历像素点设置坐标镜像;4. 使用imagecopyresampled配合负宽度可高效实现水平翻转,提升性能。

php-gd怎么翻转图片_php-gd水平垂直翻转图像

在 PHP 中使用 GD 库翻转图片,可以通过手动操作图像像素或利用 imagecopyresampled() 函数配合坐标变换来实现水平和垂直翻转。PHP 的 GD 扩展本身没有内置的直接翻转函数,但我们可以自己构造。

1. 水平翻转图像(左右翻转)

水平翻转是将图像从左到右镜像。实现方式是创建一个新图像,然后从原图的右侧开始逐列复制像素到新图的左侧。

function flipHorizontal($image) {    $width = imagesx($image);    $height = imagesy($image);    $flipped = imagecreatetruecolor($width, $height);<pre class='brush:php;toolbar:false;'>for ($x = 0; $x < $width; $x++) {    imagecopy($flipped, $image, $width - $x - 1, 0, $x, 0, 1, $height);}return $flipped;
登录后复制

}

// 使用示例$src = imagecreatefromjpeg('example.jpg');$flipped = flipHorizontal($src);imagejpeg($flipped, 'flipped_horizontal.jpg');imagedestroy($src);imagedestroy($flipped);

2. 垂直翻转图像(上下翻转)

垂直翻转是将图像从上到下镜像。原理类似,但从底部向上复制像素。

立即学习“PHP免费学习笔记(深入)”;

function flipVertical($image) {    $width = imagesx($image);    $height = imagesy($image);    $flipped = imagecreatetruecolor($width, $height);<pre class='brush:php;toolbar:false;'>for ($y = 0; $y < $height; $y++) {    imagecopy($flipped, $image, 0, $height - $y - 1, 0, $y, $width, 1);}return $flipped;
登录后复制

}

// 使用示例$src = imagecreatefrompng('example.png');$flipped = flipVertical($src);imagepng($flipped, 'flipped_vertical.png');imagedestroy($src);imagedestroy($flipped);

3. 同时水平和垂直翻转(对角翻转)

如果需要同时做水平和垂直翻转,可以组合调用上面两个函数,或者一次性完成:

图像转图像AI 图像转图像AI

利用AI轻松变形、风格化和重绘任何图像

图像转图像AI65 查看详情 图像转图像AI
function flipBoth($image) {    $width = imagesx($image);    $height = imagesy($image);    $flipped = imagecreatetruecolor($width, $height);<pre class='brush:php;toolbar:false;'>for ($x = 0; $x < $width; $x++) {    for ($y = 0; $y < $height; $y++) {        $color = imagecolorat($image, $x, $y);        imagesetpixel($flipped, $width - $x - 1, $height - $y - 1, $color);    }}return $flipped;
登录后复制

}

更高效的方式是使用 imagecopyresampled() 配合负缩放,虽然 GD 不支持直接负尺寸,但我们可以通过设置源点和宽高方向模拟:

// 更高效的水平翻转(使用 imagecopyresampled)function fastFlipHorizontal($image) {    $width = imagesx($image);    $height = imagesy($image);    $flipped = imagecreatetruecolor($width, $height);    imagecopyresampled($flipped, $image, 0, 0, $width - 1, 0, $width, $height, -$width, $height);    return $flipped;}
登录后复制

这种方法利用了 imagecopyresampled 支持负宽度的特性,实现快速水平翻转,性能更好。

基本上就这些方法,根据需求选择简单循环还是高效函数即可。

以上就是php-gd怎么翻转图片_php-gd水平垂直翻转图像的详细内容,更多请关注php中文网其它相关文章!

标签: php教程谁好
上一篇: 通过php数组函数查找元素_优化php数组函数搜索数组内容的效率
下一篇: PHP如何实现视频弹幕互动_PHP实现视频弹幕互动

推荐建站资讯

更多>