0

Some times ago i wrote a method to read out the EXIF-data from a uploaded picture in a online-community. After i got the orientation from the picture, i rotated the file in the right direction. Only a short part from my script:

public function rotate($sourceFile, $targetFile, $orienation)
{
    switch($orienation){
        case 3: $degrees = '180'; break;
        case 6: $degrees = '90'; break;
        case 8: $degrees = '270'; break;
        default: $degrees = '0';
    }

    $file = $sourceFile . DS . $targetFile;
    $rotate = GlobalConfig::BIN_IMAGICK_CONVERT . ' -rotate ' . $degrees . ' ' . $file . ' ' . $file;
    exec($rotate);
}

My script is working. But my question is, how other big guys like facebook, handle the rotation from uploaded pictures? Because my solution is certainly not the best.

johchri
  • 1
  • 1
  • Are you asking "what is the best way to perform the rotation operation" or "what is the best way to determine the image's orientation"? – DaveRandom Apr 23 '12 at 08:44
  • Note that you can use the native [ImageMagick](http://php.net/manual/fr/book.imagick.php) php extension – Boris Guéry Apr 23 '12 at 08:45
  • And at the very least, I would wrap the `exec()` if `if ($degrees)` - there is no point in rotating an image 0 degrees... – DaveRandom Apr 23 '12 at 08:46

1 Answers1

1

I believe a better approach would be to use the GD Library, the code goes something like this

// input
$image = 'myfile.jpg';

//read orientation information from EXIF

$exif = exif_read_data($filename);
$ort = $exif['IFD0']['Orientation'];

//then based on $ort you can determine the rotation degree,
//check the link below for more info

//rotation degree
$degrees = 180;

// create "image object"
$source = imagecreatefromjpeg($image) ;

// rotate
$rotate = imagerotate($source, $degrees, 0) ;

// set the header
header('Content-type: image/jpeg') ;

// output
imagejpeg($rotate) ;

more info: Exif Orientation Tag

Adi
  • 5,089
  • 6
  • 33
  • 47
  • I forgot to mention that you can also use Imagick http://php.net/manual/en/imagick.rotateimage.php – Adi Apr 23 '12 at 08:48
  • Excuse me, for my inaccurate demand. I think the difficult part of this process is, to find out in which direction must the image rotate. Because not all smartphones or cameras save the orientation. I read the orientation like this example: $exif = exif_read_data('image.jpg', 0, true); var_dump($exif['IFD0']['Orientation']); – johchri Apr 23 '12 at 09:05
  • @johchri Take a look at [this SO question](http://stackoverflow.com/questions/6726700/is-it-possible-to-detect-blur-exposure-orientation-of-an-image-programmaticall). – DaveRandom Apr 23 '12 at 09:17
  • @johchri, I updated the answer and added a link that can help you and if there was no information about the orientation stored in the image, I think you're going out of the scope of PHP questions and going more for AI – Adi Apr 23 '12 at 09:19