Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin에서 Glide로 이미지를 비트맵(Bitmap)으로 다운로드하는 방법

이 예제는 Kotlin을 사용해 Glide 라이브러리로 네트워크상의 이미지를 다운로드하고, 이를 비트맵(Bitmap) 형태로 받아와 ImageView에 표시하는 방법을 단계별로 설명합니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 정보를 모두 입력하여 프로젝트를 만듭니다.

2단계 — 레이아웃 파일 작성

다음 코드를 res/layout/activity_main.xml 파일에 추가합니다. 화면 전체를 차지하는 ImageView 하나를 배치하는 간단한 구조입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

3단계 — MainActivity.kt 작성

다음 코드를 src/MainActivity.kt에 추가합니다. 핵심은 Glide의 asBitmap() 메서드입니다. 이를 호출하면 이미지가 일반 Drawable이 아닌 Bitmap 객체로 디코딩되며, CustomTarget을 상속한 익명 객체의 onResourceReady() 콜백에서 비트맵을 전달받아 ImageView에 설정할 수 있습니다.

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.ImageView
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition;
class MainActivity : AppCompatActivity() {
    lateinit var imageView: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        imageView = findViewById(R.id.imageView)
        Glide.with(this).asBitmap().load("https://www.google.es/images/srpr/logo11w.png").into(object : CustomTarget<Bitmap?>() {
            override fun onResourceReady(resource: Bitmap, @Nullable transition: Transition<in Bitmap?>?) {
                imageView.setImageBitmap(resource)
            }
            override fun onLoadCleared(@Nullable placeholder: Drawable?) {}
        })
    }
}

참고로 onLoadCleared()는 Glide가 리소스를 해제할 때 호출되는 필수 콜백이므로, 위 예제처럼 빈 구현이라도 반드시 오버라이드해야 합니다.

4단계 — AndroidManifest.xml 설정

다음 코드를 AndroidManifest.xml에 추가합니다. 네트워크에서 이미지를 불러오기 때문에 매니페스트에 인터넷 권한(<uses-permission android:name="android.permission.INTERNET" />)이 반드시 선언되어 있어야 한다는 점에 유의하세요.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">
    <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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘Kotlin에서 Glide로 이미지를 비트맵(Bitmap)으로 다운로드하는 방법을 클릭합니다. 실행 대상 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 다운로드된 이미지가 비트맵으로 표시되는 것을 확인할 수 있습니다.

Kotlin에서 Glide로 이미지를 비트맵(Bitmap)으로 다운로드하는 방법