我需要从PHP URL保存图像到我的PC。 假设我有一个页面http://example.com/image.php,上面只有一个“花”图像,没有别的。我如何保存这个图像从一个新名称的URL(使用PHP)?
当前回答
Vartec的cURL方案对我来说并不奏效。确实,由于我的特殊问题,它有了轻微的改进。
例如,
当服务器上有重定向(比如当你试图保存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');
}
在这里,示例将远程图像保存到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');
$data = file_get_contents('http://example.com/image.php');
$img = imagecreatefromstring($data);
imagepng($img, 'test.png');
如果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);
Vartec的cURL方案对我来说并不奏效。确实,由于我的特殊问题,它有了轻微的改进。
例如,
当服务器上有重定向(比如当你试图保存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);
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- 点击下载Href图片链接
- PHP中的echo, print和print_r有什么区别?
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 用背景图像填充SVG路径元素
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?