How to flip an image horizontally and vertically using php

I search the internet for this and I cannot find what I need.

I have an image (on or off the server) and I need to flip the image horizontally or vertically using php and display it like this:

<?
$img = $_GET['img'];
header('Content-type: image/png');
/*
do the flip work
*/
imagepng($img, NULL);
imagedestroy($tmp_img);
?>

      

How can i do this? Thanks everyone.

+3


source to share


3 answers


You can also achieve this with a family of functions imagecopy

if you don't have ImageMagick available. See this example :



function ImageFlip ( $imgsrc, $mode )
{

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( $mode )
    {

        case '1': //vertical
            $src_y                =    $height -1;
            $src_height           =    -$height;
        break;

        case '2': //horizontal
            $src_x                =    $width -1;
            $src_width            =    -$width;
        break;

        case '3': //both
            $src_x                =    $width -1;
            $src_y                =    $height -1;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest                    =    imagecreatetruecolor ( $width, $height );

    if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y , $width, $height, $src_width, $src_height ) )
    {
        return $imgdest;
    }

    return $imgsrc;

}

      

+10


source


Using ImageMagick and methods flipImage()

and flopImage()

, the following example is from devzone.zend.com :

<?php
try {
  // initialize object
  $image = new Gmagick();

  // read image file
  $image->readImage('gallery/original.jpg');

  // flip image vertically
  $image->flipImage();

  // write new image file
  $image->writeImage('gallery/new_1.jpg');

  // revert
  $image->flipImage();

  // flip image horizontally
  $image->flopImage();

  // write new image file
  $image->writeImage('gallery/new_2.jpg');

  // free resource handle
  $image->destroy();
} catch (Exception $e) {
  die ($e->getMessage());
}
?>

      



With the following results:

enter image description here

+5


source


For PHP> = 5.5, you can use the imageflip built-in GD function.

+2


source







All Articles