php fopen fread图片

时间:2012-11-30 16:44:21

标签: php

我正在尝试tcp从我的linux php ec2实例到另一台服务器的图像。
当我回应fopenfread的内容时,我可以看到图像已处理但只有一半 请问有谁知道造成这种情况的原因,谢谢。

$imageURL = 'http://ec2-**-***-**-**.compute-1.amazonaws.com/New_Era_For_NASA_2.jpg';
$ch = curl_init($imageURL);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
//echo $data;
curl_close($ch);
if ($data === false) {
        die('cURL failed');
}
if ( preg_match('/Content-length: (\d+)/', $data, $matches) || preg_match('/Content-Length: (\d+)/', $data, $matches) ) {
        $size = (int)$matches[1];
}   

$fileHandle = fopen($imageURL, 'rb'); //r or rb
$fileData = fread( $fileHandle, $size );
//echo $fileData;
fclose( $fileHandle );
$data = $fileData;

header('Content-type: image/jpeg'); 
echo $data;

enter image description here

2 个答案:

答案 0 :(得分:4)

为什么要取两次? Curl可以一步完成这项工作。即。

$imageURL = 'http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Tibia_insulaechorab_transparent.png/320px-Tibia_insulaechorab_transparent.png';
$ch = curl_init($imageURL);    

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);
curl_close($ch);

if ($data === false) {
        die('cURL failed');
}

header('Content-Type: image/png');
header('Content-Length: ' . curl_getinfo( $ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD ) );
echo $data;

答案 1 :(得分:0)

$imageURL = 'http://ec2-**-***-**-**.compute-1.amazonaws.com/New_Era_For_NASA_2.jpg';
$ch = curl_init($imageURL);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
echo $data;
curl_close($ch);

就够了

file_get_content( $imageURL );

将工作到0但要注意memory_limit,fread可能是更好的选择。