在我的应用程序中,如果用户不添加图像,用户创建文章并向其添加图像,该应用程序必须在谷歌图像中搜索它并将该图像添加到用户文章。但是当我试图从谷歌获取图像。我得到这个错误:
AbstractDecoder.php line 302:
Image source not readable
控制器方法:
public function store(ArticleRequest $request)
{
if ($request->hasFile('file')) {
$file = Input::file('file');
$imgTitle = $request->title;
$imagePath = 'uploads/' . $imgTitle . '.jpg';
$request->image_path = $imagePath;
Article::create(array('title' => $request->title,
'body' => $request->body,
'image_path' => $imagePath));
Image::make($file)->resize(300, 200)->save($imagePath);
} else {
// $file = Input::file('file');
$imgTitle = $request->title;
$query = $imgTitle;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" . urlencode($query));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = json_decode(curl_exec($ch));
// $file = file_get_contents($output);
curl_close($ch);
$imagePath = 'uploads/' . $imgTitle . '.jpg';
$request->image_path = $imagePath;
Article::create(array('title' => $request->title,
'body' => $request->body,
'image_path' => $imagePath));
Image::make($output)->resize(300, 200)->save($imagePath);
}
}
答案 0 :(得分:1)
$output = json_decode(curl_exec($ch));
返回带有结果的json对象。如果你想获得第一个图片网址添加
$output = json_decode(curl_exec($ch));
if(!empty($responseData->results))
$output = $output->responseData->results[0]->url;
else {
die('no image found');
}
答案 1 :(得分:0)
我找到了解决方案
else{
$url = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=1&q=' . $request->title;
$url = file_get_contents($url);
$file = json_decode($url);
$file = $file->responseData->results[0]->url;
$imgTitle = $request->title;
$imagePath = 'uploads/' . $imgTitle . '.jpg';
$request->image_path = $imagePath;
Article::create(array('title' => $request->title,
'body' => $request->body,
'image_path' => $imagePath));
Image::make($file)->resize(300, 200)->save($imagePath);
}