본문 바로가기
C++ 200제/코딩 IT 정보

안드로이드 이미지 불러오기, 서버에서 사진 가져오기

by vicddory 2017. 4. 24.

안드로이드 이미지 불러오기, 서버에서 사진 가져오기


원격 서버로 접근해 그곳의 이미지를 불러오는 소스입니다. 서버에서 사진 가져오기할 땐, HttpURLConnection 클래스를 이용하며, 확장자 자바 파일과 main.xml 소스는 바로 아래에 있습니다.


안드로이드 이미지 불러오기 소스 : 

HTTPTest.java


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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
 
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
 
public class HTTPTest extends Activity {
     ImageView imView;
     String imageUrl="http://11.0.6.23/";
     Random r;
     
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        r= new Random();
       
        Button bt3= (Button)findViewById(R.id.get_imagebt);
        bt3.setOnClickListener(getImgListener);
        imView = (ImageView)findViewById(R.id.imview);
    }    
 
    View.OnClickListener getImgListener = new View.OnClickListener()
    {
          @Override
          public void onClick(View view) {
               int i =r.nextInt()%4;
               downloadFile(imageUrl+"png"+i+".png");
               Log.i("im url",imageUrl+"png"+i+".png");
          }
    };
 
    Bitmap bmImg;
    void downloadFile(String fileUrl){
          URL myFileUrl =null;          
          try {
               myFileUrl= new URL(fileUrl);
          } catch (MalformedURLException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
          try {
               HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
               conn.setDoInput(true);
               conn.connect();
               int length = conn.getContentLength();
               InputStream is = conn.getInputStream();
               
               bmImg = BitmapFactory.decodeStream(is);
               imView.setImageBitmap(bmImg);
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
     }
}
cs


위는 서버에서 사진 가져오기 자바 파일의 전체 소스입니다.

이중 핵심은 58~64번 라인의 소스인데, 이 부분만 아래에서 다시 보죠.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 먼저, 
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
 
// 안드로이드 이미지 크기를 불러와 스트림에 ㅓ장
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
 
// Bitmap 객체에 디코딩하여 저장
bmImg = BitmapFactory.decodeStream(is);
 
// ImageView에 안드로이드 이미지 띄움
imView.setImageBitmap(bmImg);
cs


서버에서 사진 가져오기 코드 실행 순서는 간단히 이렇게 요약됩니다.


1. HttpURLConnection 객체를 이용해 서버 접속

2. InputStream 객체를 이용해 바이트 변환

3. Bitmap 객체에 디코딩

4. ImageView 객체에 디코딩된 안드로이드 이미지를 띄움


아주 간단히 핵심만 인용한 소스입니다. 저 정도 소스만으로 테스트는 될 겁니다.

아래는 xml 파일인데 중요한 부분은 ImageView 정도네요.


안드로이드 이미지 불러오기, 서버에서 사진 가져오기[Android Imageview] 예제 소스


안드로이드 이미지 불러오기 소스 : 

main.xml


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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, HTTPImage load test"
    />
    <Button 
    android:id="@+id/get_imagebt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get an image"
    android:layout_gravity="center"
    />  
    <ImageView 
    android:id="@+id/imview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
   />
</LinearLayout>

cs


텍스트뷰는 그냥 테스트 문자열 출력하는 부분이라 빼셔도 상관없습니다. 기본적으로 ImageView만 챙겨주세요.


안드로이드 이미지 불러오기, 서버에서 사진 가져오기

댓글