Diana
Diana

Reputation: 1437

Rotate Image in PHP

I made an app that allows the user to take a picture which will then be stored on an online server. My problem is that depending on the phone some of the pictures are received rotated.

This is my php file: (I receive the picture coded in base64)

<?php

    $file_path = "photos/";
    $image = $_REQUEST['base64'];
    $name=$_REQUEST['ImageName'];

    // Decode Image
    $binary=base64_decode($image);

    $success = file_put_contents($file_path.$name, $binary); 

    if($success === false) {
       echo "Couldn't write file";
    } else {
       echo "Wrote $success bytes";
    }
    echo $name;
 ?>

I tried using this code but it doesn't change my picture orientation (maybe because I'm sending it the wrong paramaters?)

$exif = exif_read_data($binary);
$ort = $exif['IFD0']['Orientation'];
    switch($ort)
    {
        case 1: // nothing
        break;

        case 2: // horizontal flip
            $binary->flipImage($public,1);
        break;

        case 3: // 180 rotate left
            $binary->rotateImage($public,180);
        break;

        case 4: // vertical flip
            $binary->flipImage($public,2);
        break;

        case 5:// vertical flip + 90 rotate right
            $binary->flipImage($public, 2);
                $binary->rotateImage($public, -90);
        break;

        case 6: // 90 rotate right
            $binary->rotateImage($public, -90);
        break;

        case 7: // horizontal flip + 90 rotate right
            $binary->flipImage($public,1);    
            $binary->rotateImage($public, -90);
        break;

        case 8:    // 90 rotate left
            $binary->rotateImage($public, 90);
        break;
    }

Any ideas what I should change? I apologise if this may sound like a stupid question but I'm new to php.

Upvotes: 0

Views: 1220

Answers (1)

Nenad Mitic
Nenad Mitic

Reputation: 567

I would go with GD image manipulation library for rotation. Here's an example:

// Load the original file into GD
$path = __DIR__ . '/original.png';
$original = imagecreatefrompng($path);

// Rotate the image by 90 degrees
$rotated = imagerotate($original, 90, 0);

// Save the rotated image
imagepng($rotated, __DIR__ . '/rotated.png');

Upvotes: 2

Related Questions