无损图像旋转PHP

use*_*896 1 javascript php gd image-processing

我一直在研究一个旋转上传图像的系统.算法的工作原理如下:

 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.
Run Code Online (Sandbox Code Playgroud)

左右旋转90度时,此功能非常好.用户可以多次旋转无限远而不会有任何质量损失.问题是当用户试图旋转20度(或其他一些非90的倍数)时.旋转20度时,图像稍微旋转,形成黑框以填充需要填充的区域.由于图像(带有黑框)保存为png,下一次旋转20度会使图像(带黑框)再旋转20度并形成另一个黑框以消除松弛.长话短说如果你这样做到360度,你将在一个非常小的剩余图像周围有一个大的黑盒子.即使你放大并裁掉黑匣子,也会有明显的质量损失.

我有什么方法可以避开黑匣子?(服务器没有安装imagick)

Stu*_*eld 5

始终保持源文件未经修改,旋转时,使用原始源文件旋转度数.所以20度+ 20度,意味着将源旋转40度.

  1. 用户上传JPEG.
  2. 用户可以单击"90 left","90 right",或键入N度进行旋转.
  3. png打开使用

    $image = imagecreatefromjpeg("./source.jpg");
    
    Run Code Online (Sandbox Code Playgroud)
  4. png旋转......

    // 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);
    
    Run Code Online (Sandbox Code Playgroud)
  5. 如果用户希望旋转更多,则返回步骤3,否则将last.jpg视为最终并且$_SESSION["degrees"]参数被销毁.