PHP拍摄图像,旋转并将旋转的图像保存在服务器上


php take image, rotate and save rotated image on server

想要从自己的服务器拍摄图像旋转一定角度并保存图像。

图像文件$filename = 'kitten_rotated.jpg'; 有了echo '<img src='.$filename.'>';,我看到了图像。

然后

$original = imagecreatefromjpeg($filename);
$angle = 90.0;
$rotated = imagerotate($original, $angle, 0);

基于这个 https://stackoverflow.com/a/3693075/2118559 答案尝试创建图像文件

$output = 'google.com.jpg';

如果我使用新文件名保存相同的图像,则一切正常

file_put_contents( $output, file_get_contents($filename) );

但是如果我尝试保存旋转的图像,那么file_put_contents(): supplied resource is not a valid stream resource.

file_put_contents( $output, $rotated );

在这里 https://stackoverflow.com/a/12185462/2118559 阅读$export is going to be a GD image handle. It is NOT something you can simply dump out to a file and expect to get a JPG or PNG image..但无法理解如何使用该答案中的代码。

如何从$rotated创建图像文件?

尝试基于此 http://php.net/manual/en/function.imagecreatefromstring.php 进行实验

$fh = fopen( 'some_name.png' , 'w') or die("can't open file");
fwrite($fh, $data );
fclose($fh);

这是否意味着需要类似的东西

$data = base64_encode($rotated);

然后写入新文件?

我还没有测试过这个,但我认为你需要先将图像编码为 base 64。

如果您从任何图像 URL 检查字符串,则会在哈希前面看到data:image/png;base64,。将此附加到图像字符串前面并保存。

这里有一个可能会有所帮助的函数,基于你已经拥有的:

// Function settings:
// 1) Original file
// 2) Angle to rotate
// 3) Output destination (false will output to browser)
function RotateJpg($filename = '',$angle = 0,$savename = false)
    {
        // Your original file
        $original   =   imagecreatefromjpeg($filename);
        // Rotate
        $rotated    =   imagerotate($original, $angle, 0);
        // If you have no destination, save to browser
        if($savename == false) {
                header('Content-Type: image/jpeg');
                imagejpeg($rotated);
            }
        else
            // Save to a directory with a new filename
            imagejpeg($rotated,$savename);
        // Standard destroy command
        imagedestroy($rotated);
    }
// Base image
$filename   =   'http://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg';
// Destination, including document root (you may have a defined root to use)
$saveto     =   $_SERVER['DOCUMENT_ROOT']."/images/test.jpg";
// Apply function
RotateJpg($filename,90,$saveto);

如果你想保存图像,只需使用GD库函数之一:imagepng((或imagepng((。

imagerotate(( 返回图像资源,所以这不像字符串。

在您的情况下,只需保存旋转图像:

imagejpg($rotated, $output);

现在,您可以使用$output变量作为新文件名,以像以前一样包含在视图中:

echo '<img src='.$output.'>';

不要忘记在保存图像的目录中包含适当的权限。