2012-10-15 80 views
1

我一直在系統上旋轉上傳的圖像。該算法的工作原理如下:無損圖像旋轉PHP

1) User uploads a jpeg. It gets saved as a PNG 
2) Link to the temp png is returned to the user. 
3) The user can click 90left,90right, or type in N degrees to rotate 
4) The png is opened using 

    $image = imagecreatefrompng("./fileHERE"); 

5) The png is rotated using 

    $imageRotated = imagerotate($image,$degrees,0); 

6) The png is saved and the link returned to the user. 
7) If the user wishes to rotate more go back to step 3 operating on the newly 
    saved temporary PNG, 
    else the changes are commited and the final image is saved as a jpeg. 

當左右旋轉90度時,此功能非常好。用戶可以多次旋轉無限,而不會有任何質量損失。問題是,當用戶試圖旋轉20度(或其他90倍的非倍數)。旋轉20度時,圖像會稍微旋轉,並形成一個黑色框以填充需要填充的區域。由於圖像(黑框)保存爲PNG,下一次旋轉20度會使圖像(黑框)再旋轉20度,並形成另一個黑盒來消除鬆弛。長話短說,如果你這樣做到360度,你會有一個很大的黑盒子在一個非常小的剩餘圖像周圍。即使您放大並剪出黑匣子,質量也會明顯下降。

任何方式,我可以避免黑匣子? (服務器沒有安裝imagick)

+0

https://bugs.php.net/bug.php?id=25303 – hakre

+1

不,沒有。圖像必須有正方形的角落,因爲這是標量圖像的工作原理,您必須填入某些東西。如果旋轉20度,那麼您決定實際上想旋轉40度,則必須再次從基本圖像開始,否則圖像將不可避免地在隨後的操作中衰減。對此,你幾乎沒有什麼可以做的。 – DaveRandom

+0

@hakre - 我正在使用PNG,而不是JPEG,因此 – user974896

回答

5

始終存儲未修改的源文件,並在旋轉時使用原始源文件旋轉度數。所以20度+20度,意味着旋轉源40度。

  1. 用戶上傳JPEG。
  2. 用戶可以點擊「90左」,「90右」或輸入N度來旋轉。
  3. 的PNG使用

    $image = imagecreatefromjpeg("./source.jpg"); 
    
  4. 巴布亞新幾內亞旋轉打開...

    // If this is the first time, there is no rotation data, set it up 
    if(!isset($_SESSION["degrees"])) $_SESSION["degrees"] = 0; 
    
    // Apply the new rotation 
    $_SESSION["degrees"] += $degrees; 
    
    // Rotate the image 
    $rotated = imagerotate($image, $_SESSION["degrees"], 0); 
    
    // Save the image, DO NOT MODIFY THE SOURCE FILE! 
    imagejpeg($rotated, "./last.jpg"); 
    
    // Output the image 
    header("Content-Type: image/jpeg"); 
    imagejpeg($rotated); 
    
  5. 如果用戶希望更多的旋轉,回到步驟3,否則last.jpg被視爲最終並且參數$_SESSION["degrees"]被銷燬。

+0

非常感謝(15chars) – user974896