Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】Glideライブラリで画像を読み込む方法をサンプルコード付きで解説


Glideとは?

Glideは、Androidアプリ開発で広く利用されている画像読み込みライブラリです。画像の表示やデコードはもちろん、メモリ・ディスクへの自動キャッシュやアニメーションGIFの再生などにも対応しており、シンプルなAPIで高速かつ効率的な画像処理を実現できます。

この記事では、AndroidプロジェクトにGlideを組み込み、URLから画像を読み込んで画面に表示するまでの基本手順を、サンプルコードとともにわかりやすく解説します。

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、メニューからFile ⇒ New Projectを選択します。必要事項をすべて入力して、新しいプロジェクトを作成してください。

ステップ2:build.gradle(Module:app)に依存関係を追加する

まず、build.gradle(Module:app)を開き、以下のように記述します。

apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.andy.myapplication"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

既存の記述はそのままに、dependenciesブロック内へ次の2行を追加するのがポイントです。1行目がGlide本体、2行目がアノテーション処理用コンパイラの宣言にあたります。

implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'

ステップ3:build.gradle(Project)を確認する

続いて、build.gradle(Project:Myapplication)には以下のコードを記述します。通常はプロジェクト作成時に自動生成されますが、リポジトリ設定が正しく含まれているか確認しておきましょう。

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

ステップ4:レイアウトファイルを作成する

res/layout/activity_main.xmlに以下のコードを追加します。グレー背景の中央にImageViewを配置した、シンプルな構成です。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#797979"
        android:gravity="center"
        android:orientation="vertical">
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

ステップ5:MainActivity.javaを実装する

src/MainActivity.javaに以下のコードを記述します。Glideの使い方は非常にシンプルで、Glide.with()にContextを渡し、load()で画像のURLを指定、into()で表示先のImageViewを指定するだけです。

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import com.bumptech.glide.Glide;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = findViewById(R.id.imageView);
        Glide.with(this)
                .load("https://www.tutorialspoint.com/images/tp-logo-diamond.png")
                .into(imageView);
    }
}

アプリを実行して動作を確認する

それでは、アプリを実行してみましょう。ここでは、実機のAndroidスマートフォンがPCに接続されているものとして説明します。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRunアイコンをクリックしてください。

【Android】Glideライブラリで画像を読み込む方法をサンプルコード付きで解説

実行デバイスとして自分のモバイル端末を選択すると、端末の画面にインターネットから取得した画像が表示されます。正常に動作していれば、指定したURLの画像がアプリ上に読み込まれていることが確認できます。

【Android】Glideライブラリで画像を読み込む方法をサンプルコード付きで解説

まとめ

Glideを使えば、わずか数行のコードでネットワーク上の画像を非同期に読み込み、キャッシュしながら高速に表示できます。RecyclerViewを使った一覧表示など、画像を多用するアプリでも特に効果を発揮するため、ぜひ活用してみてください。

  1. Pillowライブラリで画像を読み込み・表示する方法【Python入門】

    この記事では、PythonのPillow(PIL)ライブラリを使って画像ファイルを読み込み、画面に表示する基本的な方法を解説します。画像の読み込みと表示の仕組みPillowライブラリには、画像を開くための Image.open() メソッドが用意されています。この関数は、引数としてファイルパスまたはファイル名を文字列で受け取ります。読み込んだ画像を表示するには、別の関数である show() を使用します。この関数は引数を必要とせず、呼び出すだけでOSの既定の画像ビューアー上に画像を表示してくれます。サンプルコードfrom PIL import Image im = Image.open(te

  2. AndroidでOCRを使って画像をテキストに変換する方法【おすすめアプリ2選】

    OCR(光学文字認識)技術はここ数年で大きく進化し、画像からテキストをかなり高精度で読み取れるようになりました。スマートフォン1台で画像内の文字をそのままテキスト化できれば、わざわざパソコンに画像を転送してオンラインで変換する手間が省け、とても便利です。この記事では、Androidデバイスを使って画像をテキストに変換する方法をご紹介します。 Androidで画像をテキストに変換する方法 Google PlayストアにはOCR対応アプリが数多く公開されていますが、すべてが期待通りの精度を発揮するわけではありません。さまざまなアプリを実際に検証した結果、特に高い精度を実現していたのがMicros