When processing images, sometimes we need to flip the image, such as mirroring selfies, flipping the image vertically to achieve a certain special effect, etc. In PHP, we can easily implement this function using the imageflip() function.
This article will take you step by step to understand the basic usage of the imageflip() function and how to use it in actual projects to achieve horizontal, vertical and biaxial flip of images.
imageflip() is a function provided in the PHP GD library to flip an image resource. This function is available starting from PHP 5.5.0.
bool imageflip(GdImage $image, int $mode)
$image : A valid GD image resource.
$mode : flip mode, supports the following types:
IMG_FLIP_HORIZONTAL : horizontal flip (mirror from left to right)
IMG_FLIP_VERTICAL : vertical flip (up and down mirror)
IMG_FLIP_BOTH : Flip horizontally and vertically simultaneously (rotate 180 degrees)
Return true when the function executes successfully, otherwise return false .
<?php
// Loading the image
$image = imagecreatefromjpeg('https://m66.net/images/example.jpg');
// Determine whether the image is loaded successfully
if ($image === false) {
die('无法Loading the image');
}
// Perform horizontal flip
imageflip($image, IMG_FLIP_HORIZONTAL);
// Output image to browser
header('Content-Type: image/jpeg');
imagejpeg($image);
// Free memory
imagedestroy($image);
?>
Tip: Before running, please make sure that the server has enabled the GD library and replace the image address with your own image resource path.
imageflip($image, IMG_FLIP_VERTICAL);
imageflip($image, IMG_FLIP_BOTH);
Automatically flip the image when users upload it <br> For example, if the selfies uploaded by users are reversed left and right, they can be automatically flipped horizontally.
Image generation effects <br> Adding a flip operation when generating thumbnails or dynamic images to enhance the visual effect of the image.
Image editor function module <br> If you are developing a simple online image editor, it can provide the "flip" button function to make it easy for users to operate.
imageflip() supports any image resources created through the GD library, such as imagecreatefromjpeg() , imagecreatefrommpng() , etc.
sure. You only need to use functions such as imagejpeg() , imagepng(), etc. to save the flipped image to a file:
imagejpeg($image, 'output.jpg');
imageflip() is a simple but very practical image processing function. It can play an important role whether it is front-end display optimization, user experience improvement, or when automatically processing images on the server.
If you are developing a PHP project involving image upload or processing, you might as well try this function to make your image processing process more complete!