'2017/09/21'에 해당되는 글 1건

728x90

안드로이드에서 이미지 파일 다운로드 소스 테스트한 것을 적어둔다.


이미지가 있는 url 에서 파일명만 추출하여 파일명을 자동으로 저장하기 위해서

private String getFileName(String url) {
    // url 에서 파일 이름만 자르기(확장자 제외)
   String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
   return fileName.substring(0, fileName.lastIndexOf('.'));
}

private String getFileName(String url) {
    // url 에서 파일만 자르기
   return url.substring( url.lastIndexOf('/')+1, url.length() );
}


이미지 파일을 저장할 폴더(디렉토리)를 생성하는 메소드

private File file, dir;
private String saveFolderName = "ImageTemp";

private void MakePhtoDir(){
    //saveFolderName = "/Android/data/" + getPackageName();
    //dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), saveFolderName);
    dir = new File(Environment.getExternalStorageDirectory(), saveFolderName);
    if (!dir.exists())
        dir.mkdirs(); // make dir
}


이미지 파일은 다운로드 완료한 후에는 갤러리를 업데이트 해주어야 볼 수 있다.

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

이 한줄을 생략하면 USB 케이블 연결해서 해당 폴더를 확인해도 파일명을 다운로드 했는지 여부를 알 수가 없더라.

파일 다운로드 여부를 굳이 알 수 있게 할 것이 아니라면 생략해도 된다.


ImageView 에 출력하는 것은 아래 4줄만 적어주면 된다.

File file = new File(dir + "/" + tempFileName);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
Bitmap photoBitmap = BitmapFactory.decodeFile(file.getAbsolutePath() );
imageView.setImageBitmap(photoBitmap);


갤러리에서 저장한 이미지를 확인하려면

//저장한 이미지 확인
Intent i = new Intent(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setDataAndType(Uri.fromFile(file), "image/*"); //type 지정 (이미지)
getApplicationContext().startActivity(i);



전체 테스트 코드


Androidmanifest.xml 파일에 추가할 사항

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_photodownload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:text="사진다운로드"
        tools:layout_editor_absoluteX="239dp"
        tools:layout_editor_absoluteY="31dp" />

    <ImageView
        android:id="@+id/DNImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:layout_marginTop="30dp"
        android:background="@drawable/profile_noimage"
        android:src="@drawable/photo_base" />
</LinearLayout>

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class PhotoDownload extends Activity {
    private static String TAG = "Photo";
    TextView textView;
    ImageView imageView;
    Context context;

    ProgressBar progressBar;
    private File file, dir;
    private String savePath= "ImageTemp";
    private String FileName = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_download);
        context = this.getBaseContext();

        MakePhtoDir();

        imageView = (ImageView) findViewById(R.id.DNImageView);

        Button photo_download = (Button) findViewById(R.id.btn_photodownload);
        photo_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String imgUrl = "http://img.naver.net/static/www/u/2013/0731/nmms_224940510.gif";
                FileName = imgUrl.substring( imgUrl.lastIndexOf('/')+1, imgUrl.length() );
                DownloadPhotoFromURL downloadPhotoFromURL = new DownloadPhotoFromURL();
                // 동일한 파일이 있는지 검사
                if(new File(dir.getPath() + File.separator + FileName).exists() == false){
                    downloadPhotoFromURL.execute(imgUrl,FileName);
                } else {
                    Toast.makeText(context, "파일이 이미 존재합니다", Toast.LENGTH_SHORT).show();

                    File file = new File(dir + "/" + FileName);
                    Bitmap photoBitmap = BitmapFactory.decodeFile(file.getAbsolutePath() );
                    imageView.setImageBitmap(photoBitmap);
                }
            }
        });
    }

    private void MakePhtoDir(){
        //savePath = "/Android/data/" + getPackageName();
        //dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), savePath);
        dir = new File(Environment.getExternalStorageDirectory(), savePath );
        if (!dir.exists())
            dir.mkdirs(); // make dir
    }

    public String getRealPathFromURI(Uri contentUri) {
        // 갤러리 이미지 파일의 실제 경로 구하기
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    class DownloadPhotoFromURL extends AsyncTask<String, Integer, String> {
        int count;
        int lenghtOfFile = 0;
        InputStream input = null;
        OutputStream output = null;
        String tempFileName;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //progressBar.setProgress(0);
        }

        @Override
        protected String doInBackground(String... params) {
            tempFileName = params[1];
            file = new File(dir, params[1]); // 다운로드할 파일명
            try {
                URL url = new URL(params[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                lenghtOfFile = connection.getContentLength(); // 파일 크기를 가져옴

//                if (file.exists()) {
//                    file.delete();
//                    Log.d(TAG, "file deleted...");
//                }

                input = new BufferedInputStream(url.openStream());
                output = new FileOutputStream(file);
                byte data[] = new byte[1024];
                long total = 0;

                while ((count = input.read(data)) != -1) {
                    if (isCancelled()) {
                        input.close();
                        return String.valueOf(-1);
                    }
                    total = total + count;
                    if (lenghtOfFile > 0) { // 파일 총 크기가 0 보다 크면
                        publishProgress((int) (total * 100 / lenghtOfFile));
                    }
                    output.write(data, 0, count); // 파일에 데이터를 기록
                }

                output.flush();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    }
                    catch(IOException ioex) {
                    }
                }
                if (output != null) {
                    try {
                        output.close();
                    }
                    catch(IOException ioex) {
                    }
                }
            }
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // 백그라운드 작업의 진행상태를 표시하기 위해서 호출하는 메소드
            //progressBar.setProgress(progress[0]);
            //textView.setText("다운로드 : " + progress[0] + "%");
        }

        protected void onPostExecute(String result) {
            // pdLoading.dismiss();
            if (result == null) {
                Toast.makeText(getApplicationContext(), "다운로드 완료되었습니다.", Toast.LENGTH_LONG).show();

                File file = new File(dir + "/" + tempFileName);
                //이미지 스캔해서 갤러리 업데이트
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                Bitmap photoBitmap = BitmapFactory.decodeFile(file.getAbsolutePath() );
                imageView.setImageBitmap(photoBitmap);
            } else {
                Toast.makeText(getApplicationContext(), "다운로드 에러", Toast.LENGTH_LONG).show();
            }
        }
    }
}


블로그 이미지

Link2Me

,