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