loading

How to Preview and Rotate Image Before Upload using jQuery and PHP

How to Preview and Rotate Image Before Upload using jQuery and PHP

How to Preview and Rotate Image Before Upload using jQuery and PHP

0 Sales

Free

When uploading photographs to the server, the Rotate Image Before Upload tool allows the user to correct the photo orientation. The user may utilise this function to preview the image and fix the orientation before uploading it. When you wish to examine the picture orientation and rotate the image before uploading, the image rotation capability comes in handy.

Using jQuery, it is simple to preview a picture before uploading it and to rotate an image element. You can use PHP to rotate a picture at a certain angle and upload it to a server. In this article, we will demonstrate how to preview an image via jQuery and rotate an image before uploading it to the server with PHP.

 

The following features will be included in the sample picture rotate script.

 - Using JavaScript, provide a peek of the chosen picture.

 - Using jQuery, rotate the picture clockwise or anticlockwise (client-side).

 - Using PHP, rotate a picture by the supplied angle in degrees (server-side).

 - The rotated image should now be uploaded to the server.

Image Upload Form

Make an HTML form with a file input field (to pick an image file), a hidden input field (to indicate 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

Create an HTML element to display the picture preview.

 - The picture is rotated anticlockwise by pressing the left button.

 - The picture is rotated clockwise by pressing the Rigth button.

<div class="img-preview" style="display: none;">
    <button id="rleft">Left</button>
    <button id="rright">Right</button>
    <div id="imgPreview"></div>
</div>

jQuery Library

Because jQuery is required to add, delete, and rotate image elements, you must first include the jQuery library.

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

 

Read File Data using JavaScript

filePreview() is a JavaScript method that produces an image view.

 - The FileReader object is used to read the image's raw file data using JavaScript.

 - jQuery is used to attach the picture preview to the HTML element once the image raw material has been loaded.

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

When an image file is chosen, the filePreview() method displays a preview under the given element.

 - Using the jQuery change() technique, the filePreview() function is called when the file input changes.

 - On the web page, the filePreview() method displays a preview of the specified picture.

$("#file").change(function (){
    // Image preview
    filePreview(this);
});

 

Rotate Image using jQuery

Using jQuery, the following program rotates the picture by adjusting the transform attribute of the element.

On the incidence of a left/right button click,

- To rotate the image element, the rotation degree is determined depending on the angle specified and the transform attribute set.

 - Set the rotation input field's degree value for server-side usage.

$(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

Following form submission, the selected file is transferred to the server-side script (upload.php) to begin the PHP upload process.

 - In PHP, use the $_FILES method to get the file data.

 - Using the PHP $_POST method, you may obtain the rotation degree.

 - Imagecreatefrompng(), imagecreatefromgif(), or imagecreatefromjpeg() can be used to create a new image from a file.

 - Using the imagerotate() method, you may rotate an image by specifying an angle.

 - If the rotation orientation is not given, use the move uploaded file() method to upload the picture to the server.

<?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>'; 
} 
?>

Conclusion

Our PHP example code will show you how to rotate a picture before uploading it to the server. The picture preview tool simplifies the image upload procedure. The picture orientation change feature enhances the image upload capabilities. Our sample code shows how to rotate an image on the client-side using a CSS attribute and then upload the rotated picture to the website using PHP. You may simply extend the functionality of the View and Flip Picture Prior Upload script to meet your own requirements.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 24, 2022

Updated Date : Jan 24, 2022

Ratings

Comments : 0

Downloads : 0