如何将图像保存在文件夹中?

时间:2017-03-10 13:34:58

标签: php

这是我在服务器上保存外部图像的代码。它确实有效。

$imgfromurl = file_get_contents('http://www.lavanguardia.com/r/GODO/LV/p4/WebSite/2017/03/07/Recortada/img_lbernaus_20170307-110204_imagenes_lv_terceros_istock-578792430-kUN-U42609284081yLC-992x558@LaVanguardia-Web.jpg');

$im = imagecreatefromstring($imgfromurl);

$width = imagesx($im);

$height = imagesy($im);

$newwidth = $width/2;

$newheight = $height /2;

$thumb = imagecreatetruecolor($newwidth, $newheight);

imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

$newsimgpath = uniqid().'.jpg';
$imgjpeg = imagejpeg($thumb, $newsimgpath); //save image as jpg

imagedestroy($thumb); 

imagedestroy($im);

但如果我想将图像保存在文件夹中,它就不再起作用了。

我试图改变这个:

$imgjpeg = imagejpeg($thumb, $newsimgpath);

到这个

imagejpeg($thumb, '/imgnews/'.$newsimgpath);

或者这个:

imagejpeg($thumb, realpath(dirname(__FILE__)).'/imgnews/'.$newsimgpath);

但图片未保存在该文件夹中(具有权限777)。

为什么?

编辑:

error_log中:

[10-Mar-2017 08:52:32 America/New_York] PHP Warning:  imagejpeg(/home/xxx/public_html/imgnews/58c2afa0c2c4b.jpg): failed to open stream: No such file or directory in /home/xxx/public_html/ad.php on line 14

1 个答案:

答案 0 :(得分:2)

如错误中所示 - 您没有该目录。

如您的图片所示 - http://i.imgur.com/MoKGyF6.png您有newsimg目录。

你有两个选择:

  • 创建目录imgnews
  • 在您的代码中将imgnews更改为newsimg