2015-09-15 26 views
1

在我的應用程序用戶創建文章並向其添加圖像,如果用戶不會添加圖像,該應用程序必須在谷歌圖像中搜索並將該圖像添加到用戶文章。但是,當我試圖從谷歌獲取圖像。林得到這個錯誤:Laravel iIntervention圖像。圖像源不可讀

 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); 

     } 

    } 

回答

1
$output = json_decode(curl_exec($ch)); 

返回與結果的JSON對象。如果你想獲得第一圖像URL添加

$output = json_decode(curl_exec($ch)); 
if(!empty($responseData->results)) 
    $output = $output->responseData->results[0]->url; 
else { 
    die('no image found'); 
} 
+0

現在,我得到了一個未定義的變量:輸出 – qr11

+0

添加新行'$輸出= json_decode下( curl_exec($ ch));' – mimo

+0

如果你正確地得到了'$ output = json_decode(curl_exec($ ch)); $ output = $ output-> responseData-> results [0] - > url;'Bur now Im get:試圖獲取非對象的屬性 – qr11

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); 
    }