In PHP, image processing is one of the most common needs. When using the GD library to process images, you may encounter situations where you need to flip the image. PHP provides two commonly used parameters to implement image flip: IMG_FLIP_HORIZONTAL and IMG_FLIP_VERTICAL . These two parameters represent the flip of the image in the horizontal and vertical directions respectively. Let’s introduce in detail their differences and how to use these two parameters to flip the image.
IMG_FLIP_HORIZONTAL is a commonly used parameter that flips the image horizontally, that is, exchanges the left and right positions of the image. As you can imagine, it's like placing an image in front of a mirror, and the mirroring effect turns the left side of the image into the right side and the right side into the left side.
IMG_FLIP_VERTICAL is another commonly used parameter for flipping the image vertically, in other words, the upper and lower parts of the image are interchanged. You can understand it as turning the image inverted, the top of the image becomes the bottom, and the bottom becomes the top.
The main difference between these two parameters is the direction of the flip: IMG_FLIP_HORIZONTAL is a flip in the horizontal direction, while IMG_FLIP_VERTICAL is a flip in the vertical direction.
In PHP, flipping images usually uses the imageflip() function. This function takes two parameters: an image resource and a flip mode. The flip mode is the constant you want to use, which can be IMG_FLIP_HORIZONTAL or IMG_FLIP_VERTICAL .
Assuming you already have an image file, the following code shows how to use these two parameters to flip the image.
<?php
// Loading pictures
$image = imagecreatefromjpeg('path_to_your_image.jpg');
// Horizontal flip
imageflip($image, IMG_FLIP_HORIZONTAL);
imagejpeg($image, 'flipped_horizontal.jpg'); // Save the flipped image
// Vertical flip
$image = imagecreatefromjpeg('path_to_your_image.jpg'); // 重新Loading pictures
imageflip($image, IMG_FLIP_VERTICAL);
imagejpeg($image, 'flipped_vertical.jpg'); // Save the flipped image
// Free memory
imagedestroy($image);
?>
imagecreatefromjpeg() : This function loads a JPEG image and returns an image resource.
imageflip() : This function is used to flip an image and receives two parameters: image resource and flip mode ( IMG_FLIP_HORIZONTAL or IMG_FLIP_VERTICAL ).
imagejpeg() : This function saves the image in JPEG format. You can specify a file path to save the flipped image.
imagedestroy() : Destroy image resources and free memory.
IMG_FLIP_HORIZONTAL is used to flip images horizontally (left and left and right exchange).
IMG_FLIP_VERTICAL is used to flip images vertically (up and down exchange).
When using the imageflip() function, select the appropriate flip mode to achieve the desired effect.
These two flip operations can help you easily achieve image orientation conversion in PHP image processing. Whether it is to create mirror effects or invert image operations, it is very practical.