我需要从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);
如果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);
在这里,示例将远程图像保存到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');
我不能得到任何其他解决方案的工作,但我能够使用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');
}
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);
$img_file='http://www.somedomain.com/someimage.jpg'
$img_file=file_get_contents($img_file);
$file_loc=$_SERVER['DOCUMENT_ROOT'].'/some_dir/test.jpg';
$file_handler=fopen($file_loc,'w');
if(fwrite($file_handler,$img_file)==false){
echo 'error';
}
fclose($file_handler);
使用PHP的函数copy():
copy('http://example.com/image.php', 'local/folder/flower.jpg');
注意:这需要allow_url_fopen
参见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)
$data = file_get_contents('http://example.com/image.php');
$img = imagecreatefromstring($data);
imagepng($img, 'test.png');
这里的答案都没有提到URL图像可以压缩(gzip)这一事实,而且在本例中都不起作用。
有两种解决方案可以帮助你解决这个问题:
第一个是使用cURL方法并设置curl_setopt CURLOPT_ENCODING, ":
// ... image validation ...
// Handle compression & redirection automatically
$ch = curl_init($image_url);
$fp = fopen($dest_path, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
// Exclude header data
curl_setopt($ch, CURLOPT_HEADER, 0);
// Follow redirected location
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Auto detect decoding of the response | identity, deflate, & gzip
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_exec($ch);
curl_close($ch);
fclose($fp);
它确实有效,但从对不同图像(png, jpg, ico, gif, svg)的数百个测试来看,这不是最可靠的方法。
最有效的方法是检测图像url是否有内容编码(例如gzip):
// ... image validation ...
// Fetch all headers from URL
$data = get_headers($image_url, true);
// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;
// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;
if ($gzip_decode)
{
// Get contents and use gzdecode to "unzip" data
file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
// Use copy method
copy($image_url, $dest_path);
}
有关gzdecode的更多信息,请参阅此线程。到目前为止,这工作得很好。如果有什么可以做得更好,请在下面的评论中告诉我们。