본문 바로가기
MOBILE/Android

안드로이드 ImageView 에 이미지를 URL로 가져와서 뿌려주는 방법

by 지구 2018. 8. 3.

android ImageView 에 이미지를 URL로 가져와서 뿌려주는 방법

출처 : http://apphappy.tistory.com/131



나는 이미지를 한 화면에서만 보여줄게 아니라서 재사용할 수 있도록 아예 Bean 으로 빼놔서 사용했다.

참고참고.

아, URL 로 작업하는 부분이라 Bean 안에 메소드는 별도의 Thread 에서 돌도록 처리함.


* Activity / Fragment 에서 호출하여 사용하는 방법 *

1
2
3
4
5
6
7
imgPath = getString(R.string.ip)+"/images/profile/"+user.getProfileImg();
LoadImage loadImage = new LoadImage(imgPath);
bitmap = loadImage.getBitmap();
userProfileImg.setImageBitmap(bitmap);
//아래 두 줄은 이미지를 원형으로 보이게끔 하는 소스 //근데 배경이 검은색으로 나와서 잠시 주석처리 함
/*userProfileImg.setBackground(new ShapeDrawable(new OvalShape()));
userProfileImg.setClipToOutline(true);*/
cs


* LoadImage Bean *

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.nadri.util;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
//프로필사진을 외부에서 받아 ImageView에 씌우는 메소드
public class LoadImage {
 
    private String imgPath;
    private Bitmap bitmap;
 
    public LoadImage(String imgPath){
        this.imgPath = imgPath;
    }
 
    public Bitmap getBitmap(){
        Thread imgThread = new Thread(){
            @Override
            public void run(){
                try {
                    URL url = new URL(imgPath);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                }catch (IOException e){
                }
            }
        };
        imgThread.start();
        try{
            imgThread.join();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            return bitmap;
        }
    }
 
}
 
cs


반응형

댓글