AndroidアプリでURLからビットマップ(Bitmap)を取得する方法を解説
はじめに
この記事では、Androidアプリで指定したURLからビットマップ画像を取得して画面に表示する方法を、サンプルコードとともに段階的に解説します。ネットワーク上の画像を取得する処理は、AsyncTaskを使ってバックグラウンドで実行するのがポイントです。
手順1:新しいプロジェクトを作成する
まず、Android Studioを開き、「File」→「New Project」を選択して、必要な情報を入力し、新しいプロジェクトを作成します。
手順2:レイアウトファイル(activity_main.xml)を編集する
次に、res/layout/activity_main.xmlに以下のコードを追加します。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:layout_margin="15dp"
android:src="@drawable/image"/>
</LinearLayout>
<ImageView
android:id="@+id/iMageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="20sp"/>
</LinearLayout>
このレイアウトでは、プレースホルダー用の小さなImageViewと、取得した画像を表示するための大きなImageViewを配置しています。
手順3:画像ファイルをdrawableフォルダに追加する
表示確認用として、任意の画像ファイル(.png / .jpg / .jpeg形式)をres/drawableフォルダにコピー&ペーストしておきましょう。
手順4:MainActivity.javaを実装する
src/MainActivity.javaに以下のコードを追加します。
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Bitmap bitmap;
ImageView image;
String urlImage = "https://thumbs.dreamstime.com/z/hands-holding-blue-earth-cloud-sky" + "-elements-imag-background-image-furnished-nasa-61052787.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = findViewById(R.id.iMageView);
new GetImageFromUrl(image).execute(urlImage);
}
public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap>{
ImageView imageView;
public GetImageFromUrl(ImageView img){
this.imageView = img;
}
@Override
protected Bitmap doInBackground(String... url) {
String stringUrl = url[0];
bitmap = null;
InputStream inputStream;
try {
inputStream = new java.net.URL(stringUrl).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap){
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}
}
このコードの仕組みは以下の通りです。
- onCreateメソッド内で、GetImageFromUrlクラスのインスタンスを生成し、executeメソッドで画像URLを渡して非同期処理を開始します。
- doInBackgroundメソッド内で、URLからInputStreamを開き、BitmapFactory.decodeStreamを使ってビットマップに変換します。ネットワーク通信はUIスレッドでは行えないため、この処理が必須です。
- onPostExecuteメソッド内で、取得したビットマップをImageViewにセットして画面に表示します。
手順5:AndroidManifest.xmlに権限を追加する
ネットワーク通信を行うため、androidManifest.xmlにインターネット権限を追加する必要があります。
<?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"/>
<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スマートフォンがPCに接続されているものとします。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。表示された選択肢から接続中のモバイルデバイスを選択すると、実機の画面に結果が表示されます。

まとめ
このように、AsyncTaskを活用すれば、UIスレッドをブロックすることなく、URLからビットマップ画像を取得して画面に表示できます。なお、近年のAndroid開発では、CoroutineやGlide・Coilなどの画像読み込みライブラリを使う方法も一般的なので、目的に応じて使い分けることをおすすめします。
-
Androidでビットマップから円形領域を切り抜く方法を解説
Androidでビットマップから円形領域を切り抜く方法 このチュートリアルでは、Androidアプリでビットマップ画像から円形などの任意の領域を切り抜く方法を、実際のコード例とともに解説します。サンプルでは、ユーザーが画面上を指でなぞった軌跡に沿って画像を切り抜ける、インタラクティブな実装を紹介しています。 ポイントとなるのは、Pathクラスで構築したパスと、PorterDuff.Mode.SRC_INによるピクセル合成処理です。SRC_INは「描画先(パス)と描画元(ビットマップ)が重なる部分だけを残す」モードのため、パスで囲まれた領域のみが残る切り抜き画像を生成できます。 ステップ1:新規
-
PCからAndroidアプリをインストールする方法|スマホに触れずにGoogle Play経由で導入
Webを閲覧中に気になるAndroidアプリを見つけたものの、わざわざ立ち上がってスマホを探し、Google Playストアを開いて検索してインストールするのは面倒だと感じたことはありませんか?実は、PCから直接Androidアプリをインストールすることができます。この記事では、スマホに一切触れることなく新しいアプリをAndroid端末に導入する方法を詳しく解説します。 始める前に確認しておくこと この方法を使うには、PCとAndroidスマホの両方で同じGoogleアカウントにサインインしている必要があります。事前に両端末のアカウントを揃えておきましょう。AndroidでのGoogle