Lossless image rotate PHP
I've been working on a system to rotate an uploaded image. The algorithm works as follows:
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.
This works perfectly fine when rotating 90degrees left and right. The user can rotate infinity many times without any loss in quality. The issue is that when the user tries to rotate 20 degrees (or some other non multiple of 90). When rotating 20 degrees the image is rotated slightly and a black box forms to fill the areas that need to be filled. Since the image (with the black box) is saved as a png the next rotate of 20 degrees rotates the image (with the black box) another 20 degrees and forms another black box to take up the slack. Long story short if you do this to 360 degrees you will have a large black box around a very small remaining image. Even if you zoom in and crop out the black box there is a noticeable loss in quality.
Any way I can avoid the black box? (The server does not have imagick installed)
Always store the source file unmodified and when you rotate, rotate the number of degrees using the original source file. so 20 degress + 20 degress, means rotate the source 40 degrees.
The png is opened using
$image = imagecreatefromjpeg("./source.jpg");
The png is rotated...
// 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);
If the user wishes to rotate more go back to step 3, otherwise the last.jpg is taken as final and the $_SESSION["degrees"]
parameter is destroyed.
上一篇: 如何将HTML5 Canvas作为图像保存在服务器上?
下一篇: 无损图像旋转PHP