달력

5

« 2024/5 »

  • 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
728x90
반응형
안드로이드에서는 웹상의 이미지를 자바의 입출력 메소드를 통해 쉽게 볼수 있고, 저장할 수 있다.

지난번 .txt 파일처럼 모든 파일들은 /data/data/패키지명/files/ 정해진 디렉토리로 정해져 있으며
임의 경로의 파일들은 맘대로 열수가 없다.


우선 프로젝트 생성하고, 매니페스트 파일로 가서 Pemmission을 몇개 추가해준다.

사용자 삽입 이미지


일단, 웹 링크의 이미지를 안드로이드에서 보여주는 메소드를 짜보자.
URL 주소를 통해 연결을 하고, BufferedInputStream 으로 입력을 받는다.
다시 버퍼들을 읽어 들여서 Bitmap 을 생성한다.
사용자 삽입 이미지


위에서 생성된 Bitmap 을 ImageView 에 setImageBitmap() 메소드를 통해 갖다 붙이면 된다.

사용자 삽입 이미지

난 늠른한 조지 워싱턴호의 이미지를 웹에서 퍼왔다.

사용자 삽입 이미지

다시, 웹에서 받은 이미지를 같은 방식으로 파일로 저장을 해보자.

EditText로 입력받은 파일명으로 File을 생성하고, 다운받을 웹상의 URL을 연결 후 읽어들인다.
읽어들인 버퍼들은 File을 오픈시킨후, byte단위로 쓰게된다.

사용자 삽입 이미지


이클립스 에뮬레이터의 File Explorer 로 가면 이미지가 제대로 저장되었는지 확인할 수 있다.

사용자 삽입 이미지


제대로 ImageView에서 확인가능 하다면, 이미지 파일들의 리스트를 만들어보자.
파일 목록 버튼을 클릭했을때, 에뮬레이터의 모든 파일들을 검색하고... 검색된 파일명들을 arrayList 형태로
담아서 ListView에 뿌릴 수 있게 한다.

사용자 삽입 이미지

간단하게 arrayAdapter 로 붙이면 된다.

사용자 삽입 이미지

리스트를 클릭했을때의 액션도 추가해준다.
차후에 삭제를 위해서 mCurrentId 라는 전역변수에 리스트가 클릭되었을때의 position값을 저장해두자.
사용자 삽입 이미지


삭제 모듈까지 작성하면 간단하게 코딩은 끝난다.
사용자 삽입 이미지


전체코드

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
 
import org.apache.http.util.ByteArrayBuffer;
 
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
 
public class BitmapTestActivity extends Activity {
 
	private final String URLPATH = "http://imgnews.naver.com/image/032/2010/11/24/3.jpg";
	private final String URLPATH2 = "http://image.asiatoday.co.kr/file/420612(0)-550303_57930.jpg";
	private final static String PATH = "/data/data/com.ludvan/files/";
	private final static String TAG = "filepath";
 
	ArrayList<String> itemList = new ArrayList<String>();
	ArrayAdapter<String> adapter;
	Bitmap bm;
	EditText edit, editSave;
	Toast toast;
	ListView list;
	ImageView imgView;
 
	int mCurrentId;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		Button btn1 = (Button) findViewById(R.id.Button01);
		Button btn2 = (Button) findViewById(R.id.Button02);
		Button btn3 = (Button) findViewById(R.id.Button03);
		btn1.setOnClickListener(mClickListener);
		btn2.setOnClickListener(mClickListener);
		btn3.setOnClickListener(mClickListener);
		editSave = (EditText) findViewById(R.id.EditText01);
 
		imgView = (ImageView) findViewById(R.id.ImageView01);
		ViewFromUrl(URLPATH);
		imgView.setImageBitmap(bm);
 
		list = (ListView) findViewById(R.id.list);
 
		adapter = new ArrayAdapter<String>(getApplicationContext(),
				R.layout.list_row, R.id.text01, itemList);
		list.setAdapter(adapter);
		list.setOnItemClickListener(listViewListener);
	}// main
 
	Button.OnClickListener mClickListener = new Button.OnClickListener() {
 
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
 
			case R.id.Button01:
 
				String saveName = editSave.getText().toString();
				DownloadFromUrl(URLPATH2, saveName);
 
				break;
 
			case R.id.Button02:
 
				onDelete(itemList.get(mCurrentId));
				itemList.remove(mCurrentId);
				adapter.notifyDataSetChanged();
 
				break;
 
			case R.id.Button03:
 
				onSearching(PATH);
				adapter.notifyDataSetChanged();
 
				break;
 
			default:
				break;
 
			}
		}
	};// btnListener
 
	AdapterView.OnItemClickListener listViewListener = new OnItemClickListener() {
 
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long ID) {
 
			String imgPath = PATH + itemList.get(position);
			bm = BitmapFactory.decodeFile(imgPath);
			imgView.setImageBitmap(bm);
			mCurrentId = (int) ID;
			showToast(Integer.toString(mCurrentId));
		}
	};// listViewListener
 
	private void onDelete(String mes) {
 
		File file = new File(PATH);
		File[] fList = file.listFiles();
		int count = 0;
 
		for (int i = 0; i < fList.length; i++) {
 
			String fileName = fList[i].getName();
 
			if (fileName.equals(mes)) {
 
				count++;
				fList[i].delete();
				String okmes = "지우기 성공";
				showToast(okmes);
			}
		}
		if (count < 1) {
			String errormes = "잘못된 파일 이름 입니다.";
			showToast(errormes);
		}
	}// Delete
 
	private void ViewFromUrl(String urlPath) {
 
		try {
 
			URL url = new URL(urlPath);
			URLConnection conn = url.openConnection();
			conn.connect();
			BufferedInputStream bis = new BufferedInputStream(conn
					.getInputStream(), 512 * 1024);
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
		} catch (Exception e) {
 
		}
	}// viewFromUrl
 
	private void DownloadFromUrl(String urlPath, String saveName) {
 
		String fileName = saveName + ".jpg";
		try {
 
			File file = new File(fileName);
			URL url = new URL(urlPath);
			URLConnection conn = url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
 
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer baf = new ByteArrayBuffer(50);
 
			int current = 0;
 
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}
 
			FileOutputStream fos = openFileOutput(fileName, 0);
			fos.write(baf.toByteArray());
			fos.close();
		} catch (Exception e) {
 
		}
	}// downloadfromUrl
 
	private boolean DownloadImage(String Url, String FileName) {
 
		URL imageurl;
		int Read;
 
		try {
			imageurl = new URL(Url);
 
			HttpURLConnection conn = (HttpURLConnection) imageurl
					.openConnection();
 
			int len = conn.getContentLength();
			byte[] raster = new byte[len];
 
			InputStream is = conn.getInputStream();
			FileOutputStream fos = openFileOutput(FileName, 0);
 
			for (;;) {
				Read = is.read(raster);
				if (Read <= 0) {
					break;
				}
				fos.write(raster, 0, Read);
			}
 
			is.close();
			fos.close();
			conn.disconnect();
		} catch (Exception e) {
 
			return false;
		}
		return true;
	}
 
	private void onSearching(String mes) {
 
		itemList.clear();
		File f = new File(mes);
		File[] fList = f.listFiles();
 
		if (fList != null) {
			int count = fList.length;
			for (int i = 0; i < fList.length; i++) {
				String fileName = fList[i].getName();
				itemList.add(fileName);
			}
			String countMes = Integer.toString(count);
			Toast.makeText(getApplicationContext(),
					"총 " + countMes + " 개 파일 찾았음.", Toast.LENGTH_SHORT).show();
		}
	}// Search
 
	private void showToast(String mes) {
		toast.makeText(getApplicationContext(), mes, Toast.LENGTH_SHORT).show();
	}// showToast
 
}
728x90
반응형
:
Posted by mapagilove