Home >Backend Development >PHP Tutorial >How to rotate and flip images using PHP
How to use PHP to rotate and flip images
Introduction:
In modern Internet applications, image manipulation has become an indispensable function . This article will introduce how to use PHP to rotate and flip images, and attach code examples.
1. Image rotation
Image rotation refers to rotating the image according to a certain angle. To achieve image rotation, we can use PHP's GD library.
php -i | grep -i gd
function rotateImage($sourcePath, $angle, $destinationPath) { $sourceImage = imagecreatefromjpeg($sourcePath); $rotatedImage = imagerotate($sourceImage, $angle, 0); imagejpeg($rotatedImage, $destinationPath); }
In this function, the $sourcePath parameter represents the original image path, the $angle parameter represents the rotation angle, and the $destinationPath parameter represents The output path of the rotated image.
$sourcePath = 'path/to/source/image.jpg'; $destinationPath = 'path/to/destination/image.jpg'; $angle = 90; rotateImage($sourcePath, $angle, $destinationPath);
In this example, we rotate the original image 90 degrees and save the rotated image to the target path.
2. Picture flipping
Picture flipping refers to the operation of flipping the picture horizontally or vertically. Similarly, we can use PHP's GD library to achieve image flipping.
php -i | grep -i gd
function flipImage($sourcePath, $mode, $destinationPath) { $sourceImage = imagecreatefromjpeg($sourcePath); if ($mode == 'horizontal') { $flippedImage = imageflip($sourceImage, IMG_FLIP_HORIZONTAL); } elseif ($mode == 'vertical') { $flippedImage = imageflip($sourceImage, IMG_FLIP_VERTICAL); } imagejpeg($flippedImage, $destinationPath); }
In this function, the $sourcePath parameter represents the original image path, and the $mode parameter represents the flip mode ('horizontal' represents Flip horizontally ('vertical' means vertical flip), and the $destinationPath parameter represents the output path of the flipped image.
$sourcePath = 'path/to/source/image.jpg'; $destinationPath = 'path/to/destination/image.jpg'; $mode = 'horizontal'; flipImage($sourcePath, $mode, $destinationPath);
In this example, we flip the original image horizontally and save the flipped image to the target path.
Summary:
This article introduces how to use PHP to rotate and flip images. By using the GD library, we can easily perform various operations on images and achieve richer image processing functions. Please use the above example code flexibly according to the actual situation to realize the image rotation and flipping functions you need.
The above is the detailed content of How to rotate and flip images using PHP. For more information, please follow other related articles on the PHP Chinese website!