我需要从PHP URL保存图像到我的PC。 假设我有一个页面http://example.com/image.php,上面只有一个“花”图像,没有别的。我如何保存这个图像从一个新名称的URL(使用PHP)?
当前回答
$content = file_get_contents('http://example.com/image.php');
file_put_contents('/my/folder/flower.jpg', $content);
其他回答
参见file()PHP手册:
$url = 'http://mixednews.ru/wp-content/uploads/2011/10/0ed9320413f3ba172471860e77b15587.jpg';
$img = 'miki.png';
$file = file($url);
$result = file_put_contents($img, $file)
$content = file_get_contents('http://example.com/image.php');
file_put_contents('/my/folder/flower.jpg', $content);
我不能得到任何其他解决方案的工作,但我能够使用wget:
$tempDir = '/download/file/here';
$finalDir = '/keep/file/here';
$imageUrl = 'http://www.example.com/image.jpg';
exec("cd $tempDir && wget --quiet $imageUrl");
if (!file_exists("$tempDir/image.jpg")) {
throw new Exception('Failed while trying to download image');
}
if (rename("$tempDir/image.jpg", "$finalDir/new-image-name.jpg") === false) {
throw new Exception('Failed while trying to move image file from temp dir to final dir');
}
使用PHP的函数copy():
copy('http://example.com/image.php', 'local/folder/flower.jpg');
注意:这需要allow_url_fopen
在这里,示例将远程图像保存到image.jpg。
function save_image($inPath,$outPath)
{ //Download images from remote server
$in= fopen($inPath, "rb");
$out= fopen($outPath, "wb");
while ($chunk = fread($in,8192))
{
fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
}
save_image('http://www.someimagesite.com/img.jpg','image.jpg');