How to rotate image and save the image
Asked Answered
E

6

17

In my application i have an image in a div,a button.

I want to rotate the image displayed and save the rotated image when i clicked on the button using jquery.

I already used the code:

http://code.google.com/p/jquery-rotate/

and jquery code:

$(function() {                                    // doc ready
                var rotation = 0;                             // variable to do rotation with
                $("#img").click(function() {
                    rotation = (rotation + 45) % 360; // the mod 360 probably isn't needed
                    $("#cropbox").rotate(rotation);
                });
            });

html code:

<img src="demo_files/pool.jpg" id="cropbox" />
<input type="button" id="img" name="img" value="click" />

When i using above code ,There have two images one is the old image and another is the rotated image.

Here i want to rotate the same image and displaying only the rotated image .And save the rotated image ina directory.

How can i do this using jquery? If it is not possible with jquery then how can i do it possible with php/ajax?

Endaendall answered 29/6, 2012 at 10:8 Comment(4)
You cannot save data using JavaScript. Use AJAX to save the image.Dusky
See this post 9lessons.info/2011/08/ajax-image-upload-without-refreshing.htmlDusky
i already uploaded the image using ajax.Now i want to rotate it?Endaendall
Try this: code.google.com/p/jqueryrotate/wiki/ExamplesDusky
C
32
//define image path
$filename="image.jpg";

// Load the image
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

//and save it on your server...
imagejpeg($rotate, "myNEWimage.jpg");

Take a look at:

imagerotate()

And:

file_put_contents()

Canara answered 29/6, 2012 at 12:5 Comment(4)
You actually need to use imagepng() to write the file, not file_put_contents().Sideband
Thanks. But I dont can save rotated image using file_put_contents(). I used function imagejpeg() instead.Upside
Use imagepng() or imagejpeg() instead of file_put_contents().Espinoza
simple and sweetInseminate
F
16

Image rotation: PNG or JPEG depend on file type with save on your server

// File and rotation
$rotateFilename = '/var/www/your_image.image_type'; // PATH
$degrees = 90;
$fileType = strtolower(substr('your_image.image_type', strrpos('your_image.image_type', '.') + 1));

if($fileType == 'png'){
   header('Content-type: image/png');
   $source = imagecreatefrompng($rotateFilename);
   $bgColor = imagecolorallocatealpha($source, 255, 255, 255, 127);
   // Rotate
   $rotate = imagerotate($source, $degrees, $bgColor);
   imagesavealpha($rotate, true);
   imagepng($rotate,$rotateFilename);

}

if($fileType == 'jpg' || $fileType == 'jpeg'){
   header('Content-type: image/jpeg');
   $source = imagecreatefromjpeg($rotateFilename);
   // Rotate
   $rotate = imagerotate($source, $degrees, 0);
   imagejpeg($rotate,$rotateFilename);
}

// Free the memory
imagedestroy($source);
imagedestroy($rotate);

It's works for me, try it.

Functionary answered 4/3, 2014 at 5:37 Comment(1)
Wow, what a answer, very nice, i spent whole day of rotation task in CI, after that i got it. thanks a lot GhanshyamSturgis
C
3
<?php //image rotate code here 
         if(isset($_POST['save']))
         {
             $degrees=90;

             $new_file=$sourceName;
             $filename ="http://localhost/dostoom/files_user/1000/4/153.jpg";
             $rotang = $degrees;
             list($width, $height, $type, $attr) = getimagesize($filename);
              $size = getimagesize($filename);
              switch($size['mime'])
              {
                 case 'image/jpeg':
                                     $source =
         imagecreatefromjpeg($filename);
                                     $bgColor=imageColorAllocateAlpha($source, 0, 0,
         0, 0);
                                     $rotation = imagerotate($source,
         $rotang,$bgColor);
                                     imagealphablending($rotation, false);
                                     imagesavealpha($rotation, true);
                                     imagecreate($width,$height);
                                     imagejpeg($rotation,$new_file);
                                     chmod($filename, 0777);
                 break;
                 case 'image/png':

                                     $source =
         imagecreatefrompng($filename);
                                     $bgColor=imageColorAllocateAlpha($source, 0, 0,
         0, 0);
                                     $rotation = imagerotate($source,
         $rotang,$bgColor);
                                     imagealphablending($rotation, false);
                                     imagesavealpha($rotation, true);
                                     imagecreate($width,$height);
                                     imagepng($rotation,$new_file);
                                     chmod($filename, 0777);
                 break;
                 case 'image/gif':

                                     $source =
         imagecreatefromgif($filename);
                                     $bgColor=imageColorAllocateAlpha($source, 0, 0,
         0, 0);
                                     $rotation = imagerotate($source,
         $rotang,$bgColor);
                                     imagealphablending($rotation, false);
                                     imagesavealpha($rotation, true);
                                     imagecreate($width,$height);
                                     imagegif($rotation,$new_file);
                                     chmod($filename, 0777);
                 break;
                 case 'image/vnd.wap.wbmp':
                                     $source =
         imagecreatefromwbmp($filename);
                                     $bgColor=imageColorAllocateAlpha($source, 0, 0,
         0, 0);
                                     $rotation = imagerotate($source,
         $rotang,$bgColor);
                                     imagealphablending($rotation, false);
                                     imagesavealpha($rotation, true);
                                     imagecreate($width,$height);
                                     imagewbmp($rotation,$new_file);
                                     chmod($filename, 0777);
                 break;
              }
         }

    ?>
Collectivism answered 19/6, 2014 at 17:29 Comment(0)
F
1

it will helps to rotate an image and save the image in whatever the angle image has. for example we rotated image into 180 degrees .we can save that image (180 degrees) into our folder.here we used canvas.it helps for ASP.NET developers

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" id="CLoseToggle" onclick="CloseModal()">&times;</button>
                <h4 class="modal-title">Image Preview</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12 cr-img-box">
                        <asp:Image ID="CropImg" ImageUrl="" runat="server" class="north"/>
                        <canvas id="canvas"></canvas>
                        <input type="hidden" id="hfData" runat="server"/>
                        <input type="hidden" id="hdnCropImageFileLocation"/>
                    </div>
                </div>

            </div>
            <div class="modal-footer">
                <div style="text-align: center;">
                    <input type="button" id="btnRotate" class="btn btn-sm btn-info" value="Rotate"/>
                    <asp:Button ID="OKFinalSave" class="btn btn-sm btn-info" Text="Submit" runat="server"
                                OnClick="OKFinalSave_Click"/>
                </div>
            </div>

        </div>

    </div>
</div>

protected void OKFinalSave_Click(object sender, EventArgs e)
{

    string
    CropImageLocation = ConfigurationManager.AppSettings["CropFileLocation"].ToString();
    CropImageLocation = CropImageLocation + DateTime.Now.ToString("yyyyMMdd") + "\\" + LoanNumber.Value;
    string
    a = CropImageLocation + "\\" + LoanNumber.Value + "_SIGN";
    string
    base64String = hfData.Value.Replace("data:image/png;base64,", string.Empty);
    byte[]
    bytes = Convert.FromBase64String(base64String);
    string
    filePath = a;

    if (!Directory.Exists(CropImageLocation)) {
        Directory.CreateDirectory(CropImageLocation);
    }
    if (File.Exists(a)) {
        File.Delete(CropImageLocation + "\\" + LoanNumber.Value + "_SIGN");

    }

    System.IO.File.WriteAllBytes(CropImageLocation + "\\" + LoanNumber.Value + "_SIGN.jpeg", bytes);
    SaveCropedPath(LoanNumber.Value, CropImageLocation + "\\" + LoanNumber.Value + "_SIGN.jpeg");
}


<script type = "text/javascript" >
var img = null, canvas = null;
$(function () {
    $("#canvas").css("display", "none");
    img = document.getElementById('CropImg');
    canvas = document.getElementById('canvas');
    if (!canvas || !canvas.getContext) {
        canvas.parentNode.removeChild(canvas);
    } else {
        //img.style.position = 'absolute';
        //img.style.visibility = 'hidden';
    }
    RotateImage(0);
    $('#btnRotate').click(function () {
        $("#CropImg").css("display", "none");
        $("#canvas").css("display", "block");
        if (img.className == "north") {
            RotateImage(90);
            img.className = "west";
        } else if (img.className == "west") {
            RotateImage(180);
            img.className = "south";
        } else if (img.className == "south") {
            RotateImage(270);
            img.className = "east";
        } else if (img.className == "east") {
            RotateImage(0);
            img.className = "north";
        }
    });
});

function RotateImage(degree) {
    if (document.getElementById('canvas')) {
        var context = canvas.getContext('2d');
        var cw = img.width, ch = img.height, cx = 0, cy = 0;
        switch (degree) {
            case 90:
                cw = img.height;
                ch = img.width;
                cy = img.height * (-1);
                break;
            case 180:
                cx = img.width * (-1);
                cy = img.height * (-1);
                break;
            case 270:
                cw = img.height;
                ch = img.width;
                cx = img.width * (-1);
                break;
        }
        canvas.setAttribute('width', cw);
        canvas.setAttribute('height', ch);
        context.rotate(degree * Math.PI / 180);
        context.drawImage(img, cx, cy);
        document.getElementById('hfData').value = canvas.toDataURL();
    } else {
        switch (degree) {
            case 0:
                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
                break;
            case 90:
                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';
                break;
            case 180:
                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';
                break;
            case 270:
                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
                break;
        }
    }
}

</script>
Fivestar answered 9/11, 2019 at 10:48 Comment(3)
Hi. You're replying to a post that is over 7 years old. If your post is a good answer to this question that you feel is better than the other answers already posted, could you please include some text to explain what your answer is and why it is a good answer?Chatter
it will helps to rotate an image and save the image in whatever the angle image has. for example we rotated image into 180 degrees .we can save that image (180 degrees) into our folder.here we used canvas.it helps for ASP.NET developersFivestar
Can you edit your post to update it with your description, rather than post it as a comment.Chatter
J
0

You can try my solution to rotate the image

<?php

ob_start();

// Content type
header('Content-type: image/jpeg');

class RotateImage {
    private $_path;
    private $_degrees;

    public function __construct($path, $degrees){
        $this->_path = $path;
        $this->_degrees = $degrees;
    }

    public function rotate() {
        $image = new Imagick($this->_path);
        $image->rotateimage('black', $this->_degrees);
        echo $image->getImageBlob();
        exit();
    }


}



if($_SERVER['REQUEST_METHOD'] == 'GET'){
    $sourceImagePath = isset($_GET['image_path']) ? $_GET['image_path'] : null;
    $degrees = isset($_GET['degrees']) ? $_GET['degrees'] : 90;

    $obj = new RotateImage($sourceImagePath, $degrees);
    return $obj->rotate();
}
?>
Jaunty answered 11/1, 2019 at 5:53 Comment(0)
F
0

Javascript only solution based on nagarjun daram's one using an image and a canvas.

Works with data URL, full working sample: https://jsfiddle.net/f8d46umz/7/

Beware, cross origin images may not work, at least on the fiddle.

Main rotate code:

function rotateDegrees(degrees, imgSrc, callback){
  var canvasElement = document.getElementById('canvas'); //or create
  if (!canvasElement || !canvasElement.getContext) {
    return showUnsupported();
  }
  //We use an additional img to get the sizes
  var img = document.getElementById('tmpImg'); //or create
  img.onload = function(){
      var cw = img.width,
        ch = img.height,
        cx = 0,
        cy = 0;
      switch (degrees) {
        case 90:
          cw = img.height;
          ch = img.width;
          cy = img.height * (-1);
          break;
        case 180:
          cx = img.width * (-1);
          cy = img.height * (-1);
          break;
        case 270:
          cw = img.height;
          ch = img.width;
          cx = img.width * (-1);
          break;
      }
      var context = canvas.getContext('2d');
      canvas.setAttribute('width', cw);
      canvas.setAttribute('height', ch);
      context.rotate(degrees * Math.PI / 180);
      context.drawImage(img, cx, cy);
      var result = canvas.toDataURL();
      callback && callback(result);
  }
  img.src = imgSrc;
}

Note the callback to wait for image to load into the temporary img

Follow answered 20/4, 2021 at 7:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.