2015-04-22 37 views
0

我有一些html和js代碼,從url加載圖像,並允許您旋轉它。我希望能夠在圖像旋轉後保存圖像,最好使用新的網址。如果可能的話,我還希望使用html和js來做到這一點,但我對jquery或w/e開放,否則你想到了,因爲我不知道如何做到這一點。如何在html和js旋轉後保存圖片鏈接?

<html> 
    <head> 
     <style> 
      #photoimg { 
       top: 0; 
       bottom: 0; 
       left: 0; 
       right: 0; 
      } 
      #photo { 
       position: relative; 
      } 
     </style> 
     </head> 
<form action="#" method="post"> 
    <input type="url" name="imglink" id="imglink" placeholder="Insert image URL here" /><br> 
    <input type="button" value="Show Image" id="btn1"/> 
    </form> 
     <div id="photo"></div> 
     <script> 
      document.getElementById('btn1').addEventListener('click', function(){ 
       document.getElementById('photo').innerHTML = '<img id="photoimg" src="'+ document.getElementById('imglink').value +'" alt="Image"/>'; 
       //Get larger edge 
       var largerPhotoDimension = Math.sqrt(Math.pow(document.getElementById('photoimg').offsetWidth , 2) + Math.pow(document.getElementById('photoimg').offsetHeight ,2)); 
       var marginVert = (largerPhotoDimension - document.getElementById('photoimg').offsetHeight)/2; 
       var marginHorz = (largerPhotoDimension - document.getElementById('photoimg').offsetWidth)/2; 
       //Adjust container to fix image rotated 90deg 
       document.getElementById('photo').style.marginRight = marginHorz; 
       document.getElementById('photo').style.marginLeft = marginHorz; 
       document.getElementById('photo').style.marginBottom = marginVert; 
       document.getElementById('photo').style.marginTop = marginVert;     
      }); 
     </script> 
     <button id="button">rotate</button> 
    <script> 
     document.getElementById('button').onclick = function(){ 
      var curr_value = document.getElementById('photoimg').style.transform; 
      var new_value = "rotate(90deg)"; 
      if(curr_value !== ""){ 
       var new_rotate = parseInt(curr_value.replace("rotate(","").replace(")","")) + 90; 
       new_value = "rotate(" + new_rotate + "deg)"; 
      } 
      document.getElementById('photoimg').style.transform = new_value; 
     }; 
    </script> 
    </body> 
</html> 
+1

我覺得你有什麼關於你的代碼確實誤會 - 這不觸及圖像本身,而是它改變了它的顯示方式。如果你的目標是使結果可以保存(比如照片編輯器),你應該看看使用畫布來代替(雖然它有點高級)。 –

+0

你應該發佈這個作爲答案,我會選擇它! – Stevo

回答

0

您無法使用javascript保存圖像。 你可以使用imagemagick一個php插件或另一個php插件的另一個服務器端腳本。

<?php 
    function rotateImage($imagePath, $angle, $color) { 
     $imagick = new \Imagick(realpath($imagePath)); 
     $imagick->rotateimage($color, $angle); 
     header("Content-Type: image/jpg"); 
     echo $imagick->getImageBlob(); 
    } 
?> 

這裏是它的文檔: http://php.net/manual/en/imagick.rotateimage.php

+0

該方法兼容性如何?也就是說,它適用於所有瀏覽器嗎?我會對IE8以上的任何事情感到滿意。我試圖應用漸進式增強的規則。 – Stevo

+0

是的。它是一個服務器端腳本。只要它安裝在服務器上,它就可以在所有的bowsers上運行。 –

+0

這個選項,以及使用畫布,都是我將要研究的好主意。謝謝! – Stevo