차근차근/Android
[ study ] 다이어리 어플 만들어보기 2 - 부가설명7
안드로이드 URL 이미지뷰 로드
ANDROID: HOW TO LOAD IMAGE FROM URL IN IMAGEVIEW?
Contents [hide]
Project Description
- In this tutorial, we will see how to load an image from URL into Android ImageView.
- For downloading the image from URL and loading it in ImageView, we use AsyncTask.
Environment Used
- JDK 6 (Java SE 6)
- Eclipse Indigo IDE for Java EE Developers (3.7.1)
- Android SDK 4.0.3 / 4.1 Jelly Bean
- Android Development Tools (ADT) Plugin for Eclipse (ADT version 20.0.0)
- Refer this link to setup the Android development environment
Prerequisites
Android Project
Create an Android project and name it as “ImageViewFromURL“.
strings.xml
Open res/values/strings.xml and replace it with following content.
1 2 3 4 5 | <? xml version = "1.0" encoding = "utf-8" ?> < resources > < string name = "hello" >ImageView from URL</ string > < string name = "app_name" >ImageViewFromURL</ string > </ resources > |
XML layout file
This application uses XML layout file (main.xml) to display the ImageView.
Open main.xml file in res/layout and copy the following content.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | <? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:orientation = "vertical" > < ImageView android:id = "@+id/imageView" android:layout_width = "70dp" android:layout_height = "70dp" android:contentDescription = "@string/hello" android:maxHeight = "70dp" android:maxWidth = "70dp" /> </ LinearLayout > |
Activity
In src folder, create a new Class and name it as “ImageViewFromURLActivity” in the package “com.theopentutorials.android.views” and copy the following code.
From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below.
01 02 03 04 05 06 07 08 09 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | package com.theopentutorials.android.views; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ImageView; public class ImageViewFromURLActivity extends Activity { public static final String URL = ImageView imageView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); imageView = (ImageView) findViewById(R.id.imageView); // Create an object for subclass of AsyncTask GetXMLTask task = new GetXMLTask(); // Execute the task task.execute( new String[] { URL }); } private class GetXMLTask extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... urls) { Bitmap map = null ; for (String url : urls) { map = downloadImage(url); } return map; } // Sets the Bitmap returned by doInBackground @Override protected void onPostExecute(Bitmap result) { imageView.setImageBitmap(result); } // Creates Bitmap from InputStream and returns it private Bitmap downloadImage(String url) { Bitmap bitmap = null ; InputStream stream = null ; BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inSampleSize = 1 ; try { stream = getHttpConnection(url); bitmap = BitmapFactory. decodeStream(stream, null , bmOptions); stream.close(); } catch (IOException e1) { e1.printStackTrace(); } return bitmap; } // Makes HttpURLConnection and returns InputStream private InputStream getHttpConnection(String urlString) throws IOException { InputStream stream = null ; URL url = new URL(urlString); URLConnection connection = url.openConnection(); try { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod( "GET" ); httpConnection.connect(); if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { stream = httpConnection.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return stream; } } } |
- Whenever we need to perform lengthy operation or any background operation we can use Asyntask which executes a task in background and publish results on the UI thread without having to manipulate threads and/or handlers.
- In onCreate(), we create and execute the task to load image from url. The task’s execute method invokes doInBackground() where we open a Http URL connection and create a Bitmap from InputStream and return it.
- Once the background computation finishes, onPostExecute() is invoked on the UI thread which sets the Bitmap on ImageView.
Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client.
For Gingerbread and later, HttpURLConnection is the best choice.
AndroidManifest.xml
Define the activity in AndroidManifest.xml file. To access internet from Android application set theandroid.permission.INTERNET permission in manifest file as shown below.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <? xml version = "1.0" encoding = "utf-8" ?> package = "com.theopentutorials.android.views" android:versionCode = "1" android:versionName = "1.0" > < uses-sdk android:minSdkVersion = "15" /> <!-- Allows applications to open network sockets. --> < uses-permission android:name = "android.permission.INTERNET" /> < application android:icon = "@drawable/ic_launcher" android:label = "@string/app_name" > < activity android:name = ".ImageViewFromURLActivity" android:label = "@string/app_name" > < intent-filter > < action android:name = "android.intent.action.MAIN" /> < category android:name = "android.intent.category.LAUNCHER" /> </ intent-filter > </ activity > </ application > </ manifest > |
Output
Project Folder Structure
The complete folder structure of this example is shown below.
php웹서버로 이미지 전송시 문자열변수 동시 전송 방법
http://www.androidpub.com/664496
http://www.androidpub.com/451838
자료를 보고 제가 만든 어플에서
기본 갤러리 어플을 인텐트로 불러서
이미지 Uri를 알아내고
http://www.mail-archive.com/android-developers@googlegroups.com/msg66448.html
여기에서 Uri로부터 파일의 절대경로를 구하는 방법을 알아내고
http://blog.inculab.net/28
여기 글 밑에 소스코드 다운로드 받아서 웹서버에 upload.php 로 이미지를 전송하는데 까지는 성공했어요.
근데 이미지를 아이디(문자열) 이름으로 서버에저장을 해야하기에
이미지와 (아이디(mb_id))문자열 변수를 upload.php 파일로 동시에 전송하는 방법을 알고 싶습니다.
업로드에 사용된 소스코드는 다음과 같습니다..
부탁드립니다.. (--)(__) 꾸벅..
001.
public
class
UploadTest
extends
Activity {
002.
003.
private
Button mUploadBtn;
004.
private
FileInputStream mFileInputStream =
null
;
005.
private
URL connectUrl =
null
;
006.
private
EditText mEdityEntry;
007.
008.
String lineEnd =
"\r\n"
;
009.
String twoHyphens =
"--"
;
010.
String boundary =
"*****"
;
011.
012.
Intent intent;
013.
014.
@Override
015.
protected
void
onCreate(Bundle savedInstanceState) {
016.
// TODO Auto-generated method stub
017.
super
.onCreate(savedInstanceState);
018.
019.
setContentView(R.layout.upload_test);
020.
021.
mEdityEntry = (EditText)findViewById(R.id.edit_entry);
022.
023.
intent = getIntent();
024.
mEdityEntry.setText(intent.getStringExtra(
"data_selPhotoUriPath"
));
025.
026.
mUploadBtn = (Button)findViewById(R.id.btn);
027.
mUploadBtn.setOnClickListener(
new
View.OnClickListener() {
028.
public
void
onClick(View v) {
029.
// TODO Auto-generated method stub
030.
try
{
031.
mEdityEntry.setText(
"Uploading..."
);
032.
String mFilePath = intent.getStringExtra(
"data_selPhotoUriPath"
);
033.
//String mFilePath = "/sdcard/DCIM/Camera/photo001.jpg";
034.
DoFileUpload(mFilePath);
035.
}
catch
(Exception e) {
036.
// TODO: handle exception
037.
}
038.
}
039.
});
040.
041.
}
042.
043.
private
void
DoFileUpload(String filePath)
throws
IOException {
044.
Log.d(
"Test"
,
"file path = "
+ filePath);
045.
HttpFileUpload(
"http://jumoni.com/upload.php"
,
""
, filePath);
046.
}
047.
048.
private
void
HttpFileUpload(String urlString, String params, String fileName) {
049.
try
{
050.
051.
mFileInputStream =
new
FileInputStream(fileName);
052.
connectUrl =
new
URL(urlString);
053.
Log.d(
"Test"
,
"mFileInputStream is "
+ mFileInputStream);
054.
055.
// open connection
056.
HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection();
057.
conn.setDoInput(
true
);
058.
conn.setDoOutput(
true
);
059.
conn.setUseCaches(
false
);
060.
conn.setRequestMethod(
"POST"
);
061.
conn.setRequestProperty(
"Connection"
,
"Keep-Alive"
);
062.
conn.setRequestProperty(
"Content-Type"
,
"multipart/form-data;boundary="
+ boundary);
063.
064.
// write data
065.
DataOutputStream dos =
new
DataOutputStream(conn.getOutputStream());
066.
dos.writeBytes(twoHyphens + boundary + lineEnd);
067.
dos.writeBytes(
"Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ fileName+
"\""
+ lineEnd);
068.
dos.writeBytes(lineEnd);
069.
070.
int
bytesAvailable = mFileInputStream.available();
071.
int
maxBufferSize =
1024
;
072.
int
bufferSize = Math.min(bytesAvailable, maxBufferSize);
073.
074.
byte
[] buffer =
new
byte
[bufferSize];
075.
int
bytesRead = mFileInputStream.read(buffer,
0
, bufferSize);
076.
077.
Log.d(
"Test"
,
"image byte is "
+ bytesRead);
078.
079.
// read image
080.
while
(bytesRead >
0
) {
081.
dos.write(buffer,
0
, bufferSize);
082.
bytesAvailable = mFileInputStream.available();
083.
bufferSize = Math.min(bytesAvailable, maxBufferSize);
084.
bytesRead = mFileInputStream.read(buffer,
0
, bufferSize);
085.
}
086.
087.
dos.writeBytes(lineEnd);
088.
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
089.
090.
// close streams
091.
Log.e(
"Test"
,
"File is written"
);
092.
mFileInputStream.close();
093.
dos.flush();
// finish upload...
094.
095.
// get response
096.
int
ch;
097.
InputStream is = conn.getInputStream();
098.
StringBuffer b =
new
StringBuffer();
099.
while
( ( ch = is.read() ) != -
1
){
100.
b.append( (
char
)ch );
101.
}
102.
String s=b.toString();
103.
Log.e(
"Test"
,
"result = "
+ s);
104.
mEdityEntry.setText(s);
105.
dos.close();
106.
107.
}
catch
(Exception e) {
108.
Log.d(
"Test"
,
"exception "
+ e.getMessage());
109.
// TODO: handle exception
110.
}
111.
}
112.
}
+
2010.11.09 12:43:10빨간마음육구 //param roof
for(int i =0; i<paramNames.size();i++){
dos.writeBytes(twoHyphens + boundary + lineEnd); //필드 구분자 시작
dos.writeBytes("Content-Disposition: form-data; name=\""+paramNames.get(i)+"\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(paramValues.get(i));
dos.writeBytes(lineEnd);
}
//file roof
for(int i =0; i<files.size();i++){
//======================start
// fis = new FileInputStream(files.get(files.size()-1));
fis = new FileInputStream(files.get(i));
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + files.get(i).getName() +"\""+ lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
//======================end
}
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
//저두그것때문에 고민좀했는데~~
//요런식으로 하세요 ^^
//조심할껀 필드구분자와 lineEnd가 틀리면 안돼요~
이미지 불러오기 & 서버전송
서버에 이미지 파일 업로드 소스입니다. 근데 시간이 오래 걸리네요..
http://www.androidpub.com/2139554
안드로이드/Android HttpUrlConnection Request 설명 및 설정 하기 (header, get, post, body등)
http://arabiannight.tistory.com/204
http://안드로이드와 PHP연동하기(HttpURLConnection오브젝트사용)
http://m.blog.daum.net/web_design/314
Upload File To Server - Android Example
Image File Upload Example
'차근차근 > Android' 카테고리의 다른 글
폰갭 환경만들기 1 | node.js - #2 설치와 개발환경 구축 (0) | 2016.02.01 |
---|---|
app.initialize() (0) | 2016.02.01 |
[ study ] 다이어리 어플 만들어보기 2 - 부가설명6 (0) | 2015.05.07 |
[ study ] 다이어리 어플 만들어보기 2 - 부가설명5 (0) | 2015.05.07 |
[ study ] 다이어리 어플 만들어보기 2 (0) | 2015.05.06 |
'차근차근/Android'의 다른글
- 현재글[ study ] 다이어리 어플 만들어보기 2 - 부가설명7
파일 파트의 바운드리 표시를
Content-Disposition: form-data; name="필드명";filename="파일명"
으로 했다면 일반 파라메터는
으로 만 바운드리 표시를 하시면 됩니다.Content-Disposition: form-data; name="필드명"
바운드리 바디는 URL 인코딩된 파라메터 값을 출력하시면 됩니다.
이건 POST 방식으로 데이터 보낼때고요.
짧은 크기의 파라메터라면 좀더 손쉽게 그냥 get 방식으로 전송 URL뒤에 쿼리 스트링 붙이세요
http://서버/파일전송주소.php?name=value
의 방법으로 말이죠.
물론 name과 value는 URL인코딩 하셔야 합니다.