如何将生成的图像文件移动到 PHP 中的自定义目录?

How to move generated image file to custom directory in PHP?

我正在使用下面的 PHP 代码生成一个新的图像文件并将其传输到一个新目录。但是,当我这样做时,我收到一条错误消息,指出文件名不能为空。

错误是什么?

<?php
    $file = "assets/images/posts/original/2018/Dec/22/b1132bbdf75.png";
    function processjpg($filename){
        list($width,$height) = getimagesize($filename);
        $newwidth = 870;
        $newheight = 450;
        $imagetruecolor = imagecreatetruecolor($newwidth,$newheight);
        $newimage = imagecreatefromjpeg($filename);
        imagecopyresampled($imagetruecolor,$newimage,0,0,0,0,$newwidth,$newheight,$width,$height);
        file_put_contents("/app", imagejpeg($imagetruecolor,'newjpg.jpg',100));
        echo $filename." Processed";
      };

      processjpg($file);
    exit();
?>

如果我不使用 file_put_contents 而只使用 imagejpeg($imagetruecolor,'newjpg.jpg',100) 那么默认情况下它保存在脚本执行的目录中,我希望它转移到自定义目录。

imagejpeg() 为您写入文件,您不需要 file_put_contents()

<?php
$file = "assets/images/posts/original/2018/Dec/22/b1132bbdf75.png";
function processjpg($filename)
{
    list($width, $height) = getimagesize($filename);
    $newwidth = 870;
    $newheight = 450;
    $imagetruecolor = imagecreatetruecolor($newwidth, $newheight);
    $newimage = imagecreatefromjpeg($filename);
    imagecopyresampled($imagetruecolor, $newimage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagejpeg($imagetruecolor, "/app/newjpg.jpg", 100);
    echo $filename . " Processed";
}

processjpg($file);
exit();