InstagramAPIを使って写真取得してみる

InstagramAPIを利用するには、以下の情報が必要となる

  • ユーザー名
  • ユーザーID
  • CLIENTID
  • CLIENTSECRET
  • AccessToken

1. Instagram Developer Documentationでクライアント登録

Developer Documentation
→ "ManageClients"
→ "Register new OAuth Client"
で登録する

  • Application Name
  • Description
  • Website
  • OAuth redirect_uri

登録すると、ClientID 、ClientSecret が発行される。

2. codeを取得する

取得した、"ClientID"と登録した"OAuth redirect_uri"を下記URLの対象部分へあてはめブラウザよりアクセスする。

https://api.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri[REDIRECT_URI]&response_type=code

正常にアクセスできれば、"OAuth redirect_uri"のパラメーターにcodeが付与され取得できる。

[REDIRECT_URI]?code=[CODE]

3. AccessToken、UserIDを取得する

ターミナルを開き、以下のコマンドを実行

curl \
-F 'client_id=[CLIENT_ID]' \
-F 'client_secret=[CLIENT_SECRET]' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=[OAuth_REDIRECT_URI]' \
-F 'code=[CODE]' \
https://api.instagram.com/oauth/access_token

・実行結果

{{"access_token":"[ACCESS_TOKEN]",
"user":{"username":"[USER_NAME]",
"bio":"",
"website":"[WEBSITE]",
"profile_picture":"[PROFILE_PICTURE]",
"full_name":"[FULL_NAME]",
"id":"[USER_ID]"}}

4. PHPで写真を取得する

<?php
$limit=30;
/* Instagram */
define('INSTAGRAM_USER_NAME', '[USER_NAME]');
define('INSTAGRAM_USER_ID', '[USER_ID]');
define('INSTAGRAM_ACCESS_TOKEN', '[ACCESS_TOKEN]');
define('INSTAGRAM_API_URL', 'https://api.instagram.com/v1/users/'.INSTAGRAM_USER_ID.'/media/recent?access_token='.INSTAGRAM_ACCESS_TOKEN);

$uri=INSTAGRAM_API_URL.'&count='.$limit;
$options['request_type'] = 0;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_POST, $options['request_type']);
if( !empty($options['post']) ) {
	curl_setopt($ch, CURLOPT_POSTFIELDS, $options['post']);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = json_decode(curl_exec($ch));
curl_close($ch);

MacOSX固有コマンド『sips』を使って画像のリサイズをする

基本コマンド

sips --resampleWidth 580 hoge.jpg --out hoge_thumb.jpg

一括リサイズ

for file in *.jpg; do sips --resampleWidth 580 $file --out ${file%.jpg}-thumb.jpg; done

その他sipsコマンドいろいろまとめ

説明 オプション 概要 コマンド例
画像のフォーマットを変更する -s format - sips -s format hoge.png --out hoge.jpg
画像のリサイズ(縦横比が変わるようなリサイズ) -z H W H:縦幅 W:横幅 sips -z 600 400 hoge.png --out hoge_thumb.png
画像のリサイズ(縦横比を維持してリサイズ) -Z [H or W] H:縦幅 W:横幅 sips -Z 580 hoge.png --out hoge_thumb.png
画像のリサイズ(縦幅または横幅を固定し縦横比を維持してリサイズ) --resampleWidth [サイズ] OR --resampleHeight [サイズ] - sips --resampleWidth 580 hoge.png --out hoge_thumb.png
画像を回転させる -r A A:角度 sips -r 45 hoge.png --out hoge_angle.png
画像を水平に反転 -f horizontal - sips -f horizontal hoge.png --out hoge_horizontal.png
画像を垂直に反転 -f vertical - sips -f vertical hoge.png --out hoge_vertical.png
中心から画像を切り出す -c H W H:縦幅 W:横幅 sips -c 80 60 hoge.png --out hoge_thumb.png

参考:コマンド - 画像をコマンドラインで - その1 (リサイズ / 回転 / 反転 など)