Preview and Rotate Image Before Upload using jQuery and PHP

Rotate image before upload feature allows the user to fix the photo orientation when uploading images to the server. With this feature, the user can preview the image and correct the orientation before file upload. Image rotation functionality is very useful when you want to preview the image orientation and rotate image before upload.

Preview image before upload and rotate image element functionality can be easily implemented using jQuery. You can rotate image in a specific angle and upload image to server using PHP. In this tutorial, we will show you how to preview image using jQuery and rotate image before upload to the server using PHP.

The following functionality will be integrated into the example image rotate script.

  • Display preview of the selected image using JavaScript.
  • Rotate the image clockwise or anticlockwise angle using jQuery (client-side).
  • Rotate an image using the given angle in degrees using PHP (server-side).
  • Upload the rotated image to the server.

Image Upload Form

Create an HTML form with a file input field (for select image file), hidden input (for specifying the rotation degrees) and a submit button.

<form method="post" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="file" id="file" />
    <input type="hidden" name="rotation" id="rotation" value="0"/>
    <input type="submit" name="submit" value="Upload"/>
</form>

HTML Element for Image Preview

Define an HTML element to preview the image.

  • Left button rotates the image anticlockwise.
  • Rigth button rotates the image clockwise.
<div class="img-preview" style="display: none;">
    <button id="rleft">Left</button>
    <button id="rright">Right</button>
    <div id="imgPreview"></div>
</div>

jQuery Library

The jQuery is used to add, remove, and rotate image element, so include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Read File Data using JavaScript

The filePreview() is a custom JavaScript function that generates a preview of the image.

  • The FileReader object helps to read the raw file data of the image using JavaScript.
  • Once the image raw content is loaded, the image preview appends in the HTML element using jQuery.
function filePreview(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#imgPreview + img').remove();
            $('#imgPreview').after('<img src="'+e.target.result+'" class="pic-view" width="450" height="300"/>');
        };
        reader.readAsDataURL(input.files[0]);
        $('.img-preview').show();
    }else{
        $('#imgPreview + img').remove();
        $('.img-preview').hide();
    }
}

Selected Image Preview

Once an image file is selected, the preview appears under the specified element using filePreview() function.

  • On the change event of the file input, the filePreview() function is triggered using the jQuery change() method.
  • The filePreview() function displays a preview of the selected image on the web page.
$("#file").change(function (){
    // Image preview
    filePreview(this);
});

Note that: You can use the File Type (extension) Validation using JavaScript to restrict the user to select only the image files.

Rotate Image using jQuery

The following code rotates the image by changing the transform property of the element using jQuery.

  • On Left/Right button click event,
    • The rotation degree is calculated based on the selected angle and set transform property to rotate the image element.
    • Set the degree value to the rotation input field for server-side use.
$(function() {
    var rotation = 0;
    $("#rright").click(function() {
        rotation = (rotation -90) % 360;
        $(".pic-view").css({'transform': 'rotate('+rotation+'deg)'});
		
        if(rotation != 0){
            $(".pic-view").css({'width': '300px', 'height': '300px'});
        }else{
            $(".pic-view").css({'width': '100%', 'height': '300px'});
        }
        $('#rotation').val(rotation);
    });
	
    $("#rleft").click(function() {
        rotation = (rotation + 90) % 360;
        $(".pic-view").css({'transform': 'rotate('+rotation+'deg)'});
		
        if(rotation != 0){
            $(".pic-view").css({'width': '300px', 'height': '300px'});
        }else{
            $(".pic-view").css({'width': '100%', 'height': '300px'});
        }
        $('#rotation').val(rotation);
    });
});

Rotate and Upload File to Server

After the form submission, the selected file is sent to the server-side script (upload.php) to proceed with the upload process using PHP.

  • Retrieve the file data using the $_FILES method in PHP.
  • Get the rotation degree using the PHP $_POST method.
  • Create a new image from file using imagecreatefrompng() or imagecreatefromgif() or imagecreatefromjpeg() function.
  • Rotate an image with a given angle using imagerotate() function.
  • Save rotated image on the server using imagepng() or imagegif() or imagejpeg() function.
  • If the rotation angle is not specified, upload image to server using the move_uploaded_file() function.
<?php 
$uploadPath 
'uploads/';

$statusMsg '';
$upload 0;
if(isset(
$_POST['submit'])){
    if(!empty(
$_FILES['file']['name'])){
        
$fileName $_FILES['file']['name'];
        
$fileType $_FILES['file']['type'];
        
$fileTemp $_FILES['file']['tmp_name'];
        
        
$filePath $uploadPath.basename($fileName);
        
        
// Allow certain file formats
        
$allowTypes = array('image/png','image/jpg','image/jpeg','image/gif');
        if(
in_array($fileType$allowTypes)){
            
$rotation $_POST['rotation'];
            if(
$rotation == -90 || $rotation == 270){
                
$rotation 90;
            }elseif(
$rotation == -180 || $rotation == 180){
                
$rotation 180;
            }elseif(
$rotation == -270 || $rotation == 90){
                
$rotation 270;
            }
            
            if(!empty(
$rotation)){
                switch(
$fileType){
                    case 
'image/png':
                        
$source imagecreatefrompng($fileTemp);
                        break;
                    case 
'image/gif':
                        
$source imagecreatefromgif($fileTemp);
                        break;
                    default:
                        
$source imagecreatefromjpeg($fileTemp);
                }
                
$imageRotate imagerotate($source$rotation0);
                
                switch(
$fileType){
                    case 
'image/png':
                        
$upload imagepng($imageRotate$filePath);
                        break;
                    case 
'image/gif':
                        
$upload imagegif($imageRotate$filePath);
                        break;
                    default:
                        
$upload imagejpeg($imageRotate$filePath);
                }
                 
            }elseif(
move_uploaded_file($fileTemp$filePath)){
                
$upload 1;
            }else{
                
$statusMsg 'File upload failed, please try again.';
            }
        }else{
            
$statusMsg 'Sorry, only JPG/JPEG/PNG/GIF files are allowed to upload.';
        }
    }else{
        
$statusMsg 'Please select a file to upload.';
    }
}

// Display status
if($upload == 1){
    echo 
'<h4>File has been uploaded successfully</h4>';
    echo 
'<img src="'.$filePath.'" width="450" height="300" />';
}else{
    echo 
'<h4>'.$statusMsg.'</h4>';
}
?>

Related Articles

Comments 0