如何从api url获取数据(图像)?
Api结果:
info = { "title" : "aaaaa", "image" : "bbbbb" };
Api网址:
http://www.example.com/api
代码:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/api');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $result->image;
?>
Array
(
[curlResult] => info = { "title" : "aaaaa", "image" : "bbbbb" };
[info] => Array
(
[url] => http://127.0.0.1/api.txt
[content_type] => text/plain
[http_code] => 200
[header_size] => 237
[request_size] => 55
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0
[namelookup_time] => 0
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 48
[speed_download] => 48
[speed_upload] => 0
[download_content_length] => 48
[upload_content_length] => 0
[starttransfer_time] => 0
[redirect_time] => 0
[certinfo] => Array
(
)
[primary_ip] => 127.0.0.1
[primary_port] => 80
[local_ip] => 127.0.0.1
[local_port] => 61662
[redirect_url] =>
)
[errno] => 0
[error] =>
)
答案 0 :(得分:0)
视图像是否为实际blob内容或url链接可能会改变显示图像的方式。
如果是内容,则需要获取MIME类型才能正确显示,以便设置正确的页眉。
如果是链接,请访问该网页。
答案 1 :(得分:0)
在你的api中:
这看起来:
$result = array(
"title" => "aaaaa",
"image" => "bbbbb"
);
$result["image"] = file_get_contents("path/to/your/image/file");
$result["image"] = base64_encode($result["image"]);
$result = json_encode($result);
header("Content-Type: application/json");
echo $result;
在您的代码中:
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/api');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
// Do it if you encoded image string
$image_string = base64_decode($obj->image);
// Create image from base 64 decoded string
$image = imagecreatefromstring($image_string);
// And save your image as desired type (png or jpeg)
imagepng($image, "path/to/save/your/image/as/png");
编辑:你能提供服务器端代码吗?您所使用的代码按预期工作在哪里?