AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home JavaScript jQuery & AJAX

Preview and Rotate Image Before Upload using jQuery and PHP

Preview and Rotate Image Before Upload using jQuery and PHP

Lakshika Mathur by Lakshika Mathur
December 23, 2019
Reading Time: 6 mins read
0
Preview and Rotate Image Before Upload using jQuery and PHP

Rotate Image before the upload feature permits the user to fix the photo-alignment when uploading images to the server. Therefore, the user can preview the image and correct the direction before file upload with the help of this feature. In conclusion, the Image rotation functionality is beneficial when you want to see the image orientation and rotate the image before upload.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

You can quickly implement the Preview image before upload and rotate image element functionality by using jQuery. You can rotate Image in a given angle and upload Image to the server using PHP. With the help of this tutorial, we will explain to you how to preview Image using jQuery and rotate the Image before upload to the server using PHP.

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

  • Firstly, the display preview of the selected Image using JavaScript.
  • Secondly, rotate the Image clockwise or anticlockwise angle using jQuery.
  • Thirdly, rotate an image using the given angle in degrees using PHP.
  • And lastly, upload the rotated Image to the server.

Image Upload Form       

Make 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.

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

jQuery Library            

We can use jQuery to add, remove, and rotate image elements, so take in the jQuery library first.

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

SEE ALSO: Ajax File Upload using jQuery and PHP

Read File Data using JavaScript.     

The filePreview() is a custom JavaScript function that creates a preview of the Image.

  • The FileReader object helps to read the raw file data of the Image using JavaScript.
  • Once the raw image 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

After selecting the image file, the preview seems under the specified element using filePreview()  function.

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

Rotate Image using jQuery

The following code helps to rotate the image by changing the transform property of the element using jQuery.

  • On Left/Right button click event,
    • The rotation degree is calculated grounded 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);
    });
});

SEE ALSO: Upload Multiple Images and Store in Database using PHP and MySQL

Rotate and Upload File to Server

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

  • Use the $_FILES method in PHP to retrieve the file.
  • Get the rotation degree using the PHP $_POST method.
  • Make a new image from file by using imagecreatefrompng() or imagecreatefromgif() or imagecreatefromjpeg() function.
  • Rotate an image with a specific angle by using imagerotate() function.
  • Save rotated image on the server using imagepng() or imagegif() or imagejpeg() function.
  • If the rotation angle is not mentioned or specified, upload Image to a 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, $rotation, 0); 
                 
                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

Firstly, our example code will help you to rotate an image before uploading it to the server using PHP. Secondly, the image preview feature makes the image upload process more accessible. So, the image orientation change option enhances an extra value to the image upload functionality. And at last, our example code offers an easy way to rotate the Image in the client-side using CSS property and upload a rotated image to the server using PHP. Therefore, you can quickly improve the functionality of Preview and Rotate Image Before Upload script as per your needs.

Also, read our previous blog- Dynamic Image Creation with PHP

Tags: Image UploadjQuery and PHPRotate Image
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
Form Validation using jQuery Validation Plugin
jQuery & AJAX

Form Validation using jQuery Validation Plugin

January 2, 2020
34
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
Next Post
Upload and Add Watermark to Image using PHP

Upload and Add Watermark to Image using PHP

Image Gallery CRUD with PHP and MySQL

Image Gallery CRUD with PHP and MySQL

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version