LoginSignup
1
4

More than 3 years have passed since last update.

APOD APIを用いて天文画像をダウンロードする

Posted at

Q. 天文学・宇宙科学関連の画像がほしい
A. NASAがAPODってサイト持ってますよ → http://apod.nasa.gov/

お・わ・り (ゝω・)v

🐟 ... 🐟 ... 🐟 ...

これだけだと寂しいので、画像取得の自動化を目指します。

要旨

この投稿では、NASA APIsおよび、その簡単な利用について書きます。

APODとは

天文画像が毎日掲載されるサイトです。

アーカイブに残っているもっとも古い記事は1995/06/15のもの。老舗です。

Astronomy Picture of the Day (APOD) is originated, written, coordinated, and edited since 1995 by Robert Nemiroff and Jerry Bonnell. The APOD archive contains the largest collection of annotated astronomical images on the internet.

やりたいこと

  • APODが最後に投稿した画像を、クライアントに保存する
  • 保存タイミングは、毎日のある時刻、または端末起動時とする
  • 過去画像まではこだわらない

用意するもの

APOD API

NASAよりAPIが提供されています。

Example

request
https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&start_date=2017-07-08&end_date=2017-07-10
return
[
  {
    "copyright": "T. Rector",
    "date": "2017-07-08", 
    "explanation": "Similar in size to large, bright spiral galaxies in our neighborhood, IC 342 is a mere 10 million light-years distant in the long-necked, northern constellation Camelopardalis. A sprawling island universe, IC 342 would otherwise be a prominent galaxy in our night sky, but it is hidden from clear view and only glimpsed through the veil of stars, gas and dust clouds along the plane of our own Milky Way galaxy. Even though IC 342's light is dimmed by intervening cosmic clouds, this sharp telescopic image traces the galaxy's own obscuring dust, blue star clusters, and glowing pink star forming regions along spiral arms that wind far from the galaxy's core. IC 342 may have undergone a recent burst of star formation activity and is close enough to have gravitationally influenced the evolution of the local group of galaxies and the Milky Way.", 
    "hdurl": "https://apod.nasa.gov/apod/image/1707/ic342_rector2048.jpg", 
    "media_type": "image", 
    "service_version": "v1", 
    "title": "Hidden Galaxy IC 342", 
    "url": "https://apod.nasa.gov/apod/image/1707/ic342_rector1024s.jpg"
  }, 
  /* 省略 */
] 

api_key=DEMO_KEY にてすぐにAPIを使えるようですが、下記のとおり回数制限があるようです。

DEMO_KEY Rate Limits

  • Hourly Limit: 30 requests per IP address per hour
  • Daily Limit: 50 requests per IP address per day

必要であれば、同ページのフォームにて、API Key を生成してくださいませ。

cURLするスクリプト

APIの戻りJSONをもとに、画像をクライアントに保存するスクリプトを書きます。

apod.php
<?php

$url_format = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&start_date=%s';
$saving_directory = './';
$timezone_area = 'America/New_York';

date_default_timezone_set($timezone_area);
$url = sprintf($url_format, date('Y-m-d'));

$resource = curl_init();
curl_setopt($resource, CURLOPT_HEADER, false);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, true);
curl_setopt($resource, CURLOPT_BINARYTRANSFER, true);
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_SSLVERSION,1);
$json = curl_exec($resource);

// 成功例
// $json = '[{"date":"2019-11-24","explanation":"Is this image art?  50 years ago, Apollo 12 astronaut-photographer Charles \"Pete\" Conrad recorded this masterpiece while documenting colleague Alan Bean\'s lunar soil collection activities on  Oceanus Procellarum.  The featured image is dramatic and stark.  The harsh environment of the Moon\'s Ocean of Storms is echoed in Bean\'s helmet, a perfectly composed reflection of Conrad and the lunar horizon.  Works of photojournalists originally intent on recording the human condition on planet Earth, such as Lewis W. Hine\'s images from New York City in the early 20th century, or Margaret Bourke-White\'s magazine photography are widely regarded as art.  Similarly many documentary astronomy and space images might also be appreciated for their artistic and esthetic appeal.","hdurl":"https://apod.nasa.gov/apod/image/1911/BeanConrad_Apollo12_950.jpg","media_type":"image","service_version":"v1","title":"Apollo 12: Self-Portrait","url":"https://apod.nasa.gov/apod/image/1911/BeanConrad_Apollo12_960.jpg"}]';

// 失敗例
// $json = '{"code":400,"msg":"Date must be between Jun 16, 1995 and Nov 24, 2019.","service_version":"v1"}';

if ($json === false) {
    exit(1);
}

$apod_pages = json_decode($json, true);

if (isset($apod_pages['code'])) {
    exit(1);
}

$apod_page = current($apod_pages);
$image_url = $apod_page['hdurl'];
$image_url_array = explode('/', $image_url);
$image_name = end($image_url_array);
$saving_file = $saving_directory . $image_name;

clearstatcache(true, $saving_file);
if (file_exists($saving_file)) {
    exit(0);
}

$saving_file_resource = fopen($saving_file, 'wb');
curl_setopt($resource, CURLOPT_URL, $image_url);
curl_setopt($resource, CURLOPT_FILE, $saving_file_resource);
curl_exec($resource);
curl_close($resource);
fclose($saving_file_resource);

起動設定

たとえばWindows機であれば、

  • タスクスケジューラ
  • スタートアップ

を設定し、適当なタイミングでスクリプトを動作させて、画像をダウンロードするようにします。

実施結果

基本的に毎日、指定したフォルダに新しい画像が増えるようになります。

楽しい!

おわりに

この投稿では、NASA APIsを使ってAPODから画像をダウンロードしました。

デスクトップの背景やスクリーンセーバが華やかになりますので、個人利用で楽しんでみてはいかがでしょうか。

それではごきげんよう。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4