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

안드로이드에서 URL로 ImageView에 이미지 로드하는 방법

이 튜토리얼에서는 안드로이드 앱에서 인터넷상의 이미지 URL을 받아와 ImageView에 표시하는 방법을 단계별로 살펴봅니다. 네트워크 통신은 메인 스레드에서 직접 수행할 수 없기 때문에, 이 예제에서는 AsyncTask를 활용해 백그라운드에서 이미지를 다운로드하고 완료 후 화면에 출력합니다.

1단계 — 새 프로젝트 생성

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

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 상단에는 안내 문구를, 중앙에는 이미지가 표시될 ImageView를 배치했습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load Image From URL in Android ImageView"
        android:textSize="20sp" />
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="fill_parent"
        android:layout_height="300dp"
        android:layout_marginTop="16dp" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:text="ViralAndroid.com"
        android:textSize="24sp"
        android:gravity="center|bottom"
        android:textStyle="bold" />
</LinearLayout>

3단계 — MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 내부 클래스 DownloadImageFromInternet이 URL로부터 이미지 스트림을 열어 Bitmap으로 디코딩하고, 다운로드가 끝나면 onPostExecute()에서 ImageView에 적용합니다.

package com.example.sample;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 인터넷상의 이미지 링크
        new DownloadImageFromInternet((ImageView) findViewById(R.id.image_view)).execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
    }
    private class DownloadImageFromInternet extends AsyncTask<String, Void, Bitmap> {
        ImageView imageView;
        public DownloadImageFromInternet(ImageView imageView) {
            this.imageView=imageView;
            Toast.makeText(getApplicationContext(), "Please wait, it may take a few minute...",Toast.LENGTH_SHORT).show();
        }
        protected Bitmap doInBackground(String... urls) {
            String imageURL=urls[0];
            Bitmap bimage=null;
            try {
                InputStream in=new java.net.URL(imageURL).openStream();
                bimage=BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error Message", e.getMessage());
                e.printStackTrace();
            }
            return bimage;
        }
        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
        }
    }
}

4단계 — strings.xml 작성

res/values/strings.xml 파일에 아래 문자열 리소스를 추가합니다.

<resources>
    <string name="app_name">Sample</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>

5단계 — 인터넷 권한 추가

네트워크에서 이미지를 내려받으려면 인터넷 권한 선언이 필수입니다. AndroidManifest.xml<manifest> 태그 안에 아래와 같이 권한을 추가하세요. 이 단계를 누락하면 앱이 네트워크 요청 시 오류가 발생합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 버튼을 클릭하고, 목록에서 본인의 모바일 기기를 선택하면 됩니다. 앱이 정상적으로 실행되면 기기 화면에 지정한 URL의 이미지가 로드되어 표시되는 것을 확인할 수 있습니다.

안드로이드에서 URL로 ImageView에 이미지 로드하는 방법

참고: 더 나은 대안

AsyncTask는 현재 공식적으로 지원 중단(deprecated)된 방식입니다. 실무 프로젝트에서는 Glide, Picasso, Coil 같은 이미지 로딩 라이브러리를 사용하면 캐싱과 에러 처리까지 한 줄의 코드로 손쉽게 해결할 수 있으니 참고하시기 바랍니다.