AndroidでURLから画像をダウンロードして表示する方法【サンプルコード付きで解説】
この記事では、AndroidアプリでURLを指定してインターネット上の画像をダウンロードし、画面に表示する方法を、ステップごとのサンプルコードとともにわかりやすく解説します。ネットワーク通信はメインスレッドでは行えないため、ここではAsyncTaskを使用してバックグラウンド処理として実装します。
手順1:Android Studioで新規プロジェクトを作成する
Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。
手順2:レイアウトファイル(activity_main.xml)にコードを追加する
res/layout/activity_main.xml を開き、以下のコードを記述します。画面中央に画像を表示するImageViewと、その下にダウンロードを実行するButtonを配置しています。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true"> </ImageView> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/image" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/button" /> </RelativeLayout>
手順3:MainActivity.java にダウンロード処理を実装する
src/MainActivity.java に以下のコードを追加します。ボタンをタップするとProgressDialogが表示され、バックグラウンドで画像のダウンロードが開始されます。ダウンロードが完了すると、取得したBitmapがImageViewにセットされて画面に表示されます。
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
String url = "https://images.pexels.com/photos/1226302/pexels-photo1226302.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
ImageView image;
Button button;
ProgressDialog mProgressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadImage().execute(url);
}
});
}
private class DownloadImage extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Download Image Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
@Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// URLから画像をダウンロード
InputStream input = new java.net.URL(imageURL).openStream();
// Bitmapにデコード
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
// ImageViewにBitmapをセット
image.setImageBitmap(result);
// プログレスダイアログを閉じる
mProgressDialog.dismiss();
}
}
}
コードのポイント
- doInBackground():URLからInputStreamを開き、BitmapFactory.decodeStream()でBitmapにデコードします。ネットワーク処理は必ずこのバックグラウンドスレッド内で行います。
- onPreExecute():処理開始前にプログレスダイアログを表示し、ユーザーにローディング中であることを伝えます。
- onPostExecute():ダウンロード結果のBitmapをImageViewに反映し、ダイアログを閉じます。UI操作はこのメソッド内で行います。
手順4:strings.xml に文字列リソースを追加する
res/values/strings.xml を開き、以下のコードを追加します。
<resources> <string name="app_name">Sample</string> <string name="menu_settings">設定</string> <string name="button">画像をダウンロード</string> </resources>
手順5:AndroidManifest.xml にインターネット権限を追加する
インターネットからデータを取得するため、マニフェストにandroid.permission.INTERNET権限の宣言が必須です。この宣言を忘れると通信時にエラーが発生するので注意しましょう。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.INTERNET" ></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
アプリを実行してみよう
それでは、作成したアプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続していることを前提とします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイル端末を選択して実行すると、端末に以下のような画面が表示されます。

補足:AsyncTaskは非推奨(Deprecated)になりました
なお、本記事で使用しているAsyncTaskは、API Level 30以降で非推奨となっています。最新のプロジェクトでは、GlideやCoilなどの画像読み込みライブラリを使うか、KotlinのコルーチンやWorkManagerを利用するのがおすすめです。特にGlideを使えば、数行のコードでキャッシュ管理やエラー処理も含めた高度な画像ダウンロードが簡単に実現できます。
-
【Android】Glideを使って画像をBitmapとしてダウンロード・取得する方法
本記事では、Androidアプリ開発で広く使われている画像読み込みライブラリ「Glide」を利用して、URLから画像をダウンロードし、Bitmapとして取得する方法を解説します。GlideのasBitmap()メソッドとCustomTargetを組み合わせることで、画像を簡単にBitmap形式で受け取ることができます。手順1:プロジェクトの作成と依存関係の追加まず、Android Studioで新規プロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目を入力してプロジェクトを作成しましょう。続いて、appレベルのbuild.gradle(Module
-
Androidスマホで逆画像検索を行う3つの方法【アプリ・ブラウザ対応】
特定のテーマに関連する画像を探したいときは、キーワードを入力して「画像」オプションを選ぶだけで簡単に見つけられます。しかし、その逆——画像から情報を探す「逆画像検索」となると、話は少し変わってきます。パソコンでは簡単に行える逆画像検索も、Androidデバイスではひと手間かかることがあります。この記事では、Androidスマホで逆画像検索を実行する方法をいくつかご紹介します。アプリを使ってあらゆる画像を逆検索するAndroidデバイスで確実に逆画像検索を行いたい場合は、「Image Search」というアプリをインストールしましょう。インストール後、「Open settings before