【问题标题】:How to move generated image file to custom directory in PHP?如何将生成的图像文件移动到 PHP 中的自定义目录?
【发布时间】:2019-05-22 16:05:33
【问题描述】:

我正在使用下面的 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函数中添加图片名称的路径 例如:imagejpeg($imagetruecolor,'/path/to/store/newjpg.jpg',100);

标签: php php-5.5


【解决方案1】:

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();

【讨论】:

  • 上面的代码工作正常,如我所料:)感谢更新:)
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 2017-11-28
相关资源
最近更新 更多