Current Location: Home> Latest Articles> Make a picture of the "mirror" effect

Make a picture of the "mirror" effect

M66 2025-06-03

In the world of image processing, adding a "mirror" effect to images is a common and interesting operation. The so-called "mirror" effect refers to flipping the image horizontally so that it looks like the reflection of the original image in the mirror. This operation can be implemented very easily with the help of PHP's built-in imageflip() function.

Below we will introduce how to use the imageflip() function to achieve this effect step by step.

1. Preparation

First, make sure your server environment has GD library enabled, which is the core extension of PHP for image processing.

You can use the following code to check whether the GD library is enabled:

 <?php
if (extension_loaded('gd')) {
    echo "GD library is enabled.";
} else {
    echo "GD library is not enabled.";
}
?>

If the output prompts that the GD library is enabled, you can continue with the following steps.

2. Load the original picture

We need to load an image first. Suppose we have a JPEG format image located in the /images/sample.jpg path in the root directory of the website:

 <?php
// Loading pictures
$imagePath = 'https://m66.net/images/sample.jpg';
$image = imagecreatefromjpeg($imagePath);

if (!$image) {
    die("无法Loading pictures!");
}
?>

Note: In actual applications, if the local server processes images, you should use the local file path instead of the URL. The above writing method is applicable to the demonstration of remote pictures.

3. Flip the picture

Use the imageflip() function to achieve horizontal flip. The syntax of this function is as follows:

 bool imageflip(GdImage $image, int $mode)

The pattern we use is IMG_FLIP_HORIZONTAL , which represents horizontal flip:

 <?php
// Horizontal flip
imageflip($image, IMG_FLIP_HORIZONTAL);
?>

4. Output or save pictures

Next, we can choose to output the image directly to the browser, or save it as a new file.

Method 1: Direct output to the browser

 <?php
// Image path(This example is demonstrated with a remote address)
$imagePath = 'https://m66.net/images/sample.jpg';

// Loading pictures
$image = imagecreatefromjpeg($imagePath);

if (!$image) {
    die("无法Loading pictures!");
}

// Flip the picture(Mirror effect)
imageflip($image, IMG_FLIP_HORIZONTAL);

// Save the flipped image
$savePath = 'flipped_sample.jpg';
imagejpeg($image, $savePath);
imagedestroy($image);

echo "The flipped image has been saved to:https://m66.net/$savePath";
?>