如何从时间线项目下载图像附件?

时间:2013-05-05 21:05:14

标签: php image download google-mirror-api

我为Google Glass开发了一个镜像API应用程序,我陷入了一个非常根本的问题。我想从时间轴项目中保存图像。

require_once 'config.php';
require_once 'mirror-client.php';
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_MirrorService.php';
require_once 'util.php';
require 'facebook-php-sdk/src/facebook.php';

if($_SERVER['REQUEST_METHOD'] != "POST") {
  http_send_status(400);
  exit();
}

// Parse the request body
$body = http_get_request_body();
$request = json_decode($body, true);


// A notification has come in. If there's an attached photo, bounce it back
// to the user
$user_id = $request['userToken'];
$access_token = get_credentials($user_id);

$client = get_google_api_client();
$client->setAccessToken($access_token);

// A glass service for interacting with the Mirror API
$mirror_service = new Google_MirrorService($client);

//Save image to file
$itemId = $request['itemId'];
$timeLineItem = $mirror_service->timeline->get($itemId);
$request = new Google_HttpRequest($timeLineItem['attachments'][0]['contentUrl'], 'GET',         null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
    $image = $httpRequest->getResponseBody();
    imagejpeg($image, 'test.jpg');
  } else {
    // An error occurred.
    die('This sucks! '. $httpRequest->getResponseBody());
  }

我一直收到这个错误:   PHP警告:imagejpeg()期望参数1为资源

我是php的新手,所以我担心我甚至没有走上正轨。我做错了什么?

1 个答案:

答案 0 :(得分:4)

imagejpeg的第一个参数应该是使用'imagecreatetruecolor()'http://www.php.net/manual/en/function.imagecreatetruecolor.php创建的资源

当$ httpRequest-> getResponseBody()返回图片的二进制内容时,您可以将其保存为:file_put_contents('test.jpg', $httpRequest->getResponseBody());

使用MIME base64编码数据时:  file_put_contents('test.jpg', base64_decode($httpRequest->getResponseBody()));