Rotate Images using jQuery

To add extra functionality to an image upload form, you're likely going to want to include the ability to rotate an image. Most of the time it will simply be from portrait to landscape or vise-versa. Below is a quick demonstration of the frontend - the part the user will choose an image and rotate it.

View Demo

The HTML form is fairly simple. File input, preview box, rotate actions, and rotate degree select. You may want to replace the degree select and just hard-code 90 degrees.

<form method="POST" enctype="multipart/form-data">
   <input type="file" id="file">
   <div id="preview"></div>
   <a href="#" id="counter"><- counter</a>
   <select id="degree">
   <a href="#" id="clockwise">clockwise -></a>
   <button type="submit">save image

Next we just need to setup two event listeners. One for the rotate links and the other for the file input field for the preview.

The roate event listener uses a jQuery Rotate built in function getRotateAngle() to get the current angle of rotation. From there it check the rotate select value and forces it to be positive by using Math.abs(). Next it simple adds or subtracts the rotate select value from the current rotation angle.

The image preview listen uses an HTML5 file API to read the file and onload, we just replace the preview div with the image. Please note you may want add some checks on the file to ensure it's an image.

    var a = $('img').getRotateAngle();
    var d = Math.abs($('#degree').val());
    if($(this).attr('id') == 'counter'){
        d = a - d;
    else{d = +a + +d;}

/* image preview */
    var oFReader = new FileReader();
    oFReader.onload = function (oFREvent) {
        $('#preview').html('<img src="''">');

In the next session, we will take this form and actually save the image using PHP.

comments powered by Disqus