我需要将图像从PHP URL保存到我的PC.假设我有一个页面,http://example.com/image.php
拿着一个"花"图像,没有别的.如何使用新名称(使用PHP)从URL保存此图像?
如果您已allow_url_fopen
设置为true
:
$url = 'http://example.com/image.php'; $img = '/my/folder/flower.gif'; file_put_contents($img, file_get_contents($url));
否则使用cURL:
$ch = curl_init('http://example.com/image.php'); $fp = fopen('/my/folder/flower.gif', 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp);
copy('http://example.com/image.php', 'local/folder/flower.jpg');
$content = file_get_contents('http://example.com/image.php'); file_put_contents('/my/folder/flower.jpg', $content);
在这里,示例将远程图像保存到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');
Vartec的回答与卷曲并没有为我工作.由于我的具体问题,它确实略有改善.
例如,
当服务器上有重定向时(例如当您尝试保存Facebook个人资料图像时),您将需要以下选项集:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
完整的解决方案变为:
$ch = curl_init('http://example.com/image.php'); $fp = fopen('/my/folder/flower.gif', 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); curl_close($ch); fclose($fp);
我无法使任何其他解决方案起作用,但我能够使用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'); }