php rotate image and save code example

Example 1: php image rotate upload

//START Update the user image
if(isset($_POST['user_image_id'])){

    $upload_image_id = $_POST['user_image_id'];
    $user_image = $_FILES['user_image']['name'];
    $filePath = $_FILES['user_image']['tmp_name'];

   $image = imagecreatefromstring(file_get_contents($_FILES['user_image']['tmp_name']));
    $exif = exif_read_data($filePath);
    if(!empty($exif['Orientation'])) {
        switch($exif['Orientation']) {
           case 8:
               $image = imagerotate($image,90,0);
               break;
           case 3:
               $image = imagerotate($image,180,0);
               break;
           case 6:
               $image = imagerotate($image,-90,0);
               break;
       }
   }
    // $image now contains a resource with the image oriented correctly

    //create image target to upload
    $image_target = $folder_target.basename($_FILES['user_image']['name']);

    //upload the image the and update the name of the image
    if(move_uploaded_file($_FILES['user_image']['tmp_name'], $image_target)){
        if ($conn->query("UPDATE `users` SET `image`='$user_image' WHERE `id` LIKE '$upload_image_id'")){
            echo 1;
        }else{
            echo "not update the name, Proplem";
        }
    }else{
        echo 'image not uploaded';
    }

}

Example 2: php rotate image

After some INet searches and personal try-and-failures I succeed to rotate PNG images with preserving alpha channel transparency (semi transparency).

<?php
    $filename = 'YourFile.png';
    $rotang = 20; // Rotation angle
    $source = imagecreatefrompng($filename) or die('Error opening file '.$filename);
    imagealphablending($source, false);
    imagesavealpha($source, true);

    $rotation = imagerotate($source, $rotang, imageColorAllocateAlpha($source, 0, 0, 0, 127));
    imagealphablending($rotation, false);
    imagesavealpha($rotation, true);

    header('Content-type: image/png');
    imagepng($rotation);
    imagedestroy($source);
    imagedestroy($rotation);
?>

Tags:

Php Example