Dowload Image in android


Hôm nay mình hướng dẫn các bạn làm sao để có thể load một image from trên mạng một cách dễ dàng nhanh gọn và lẹ =]] ….

Bạn chất thì nó chả có gì gọi là bảy vẻ. Nó yh chan như khi chúng ta đọc file text thôi. Có điều Android hổ trợ một method khá ưng ý , chó việc chuyển đổi một Stream về Bitmap cho việc hiển thị image. và nhớ cấu hình trong manifest

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

Source code : Download

Hình ảnh bài viết :

d1

OK . giờ chúng ta bắt đầu viết 1 class BitmapUtils.java như sau :


package com.thaihoanghai.image;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.StrictMode;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class BitmapUtils {
	 /** Loads an image from the Web and stores it in a Bitmap, which is suitable for
     *  displaying in an ImageView.
     */
	@SuppressLint("NewApi")
	public static Bitmap bitmapFromUrl(String urlString) throws MalformedURLException,IOException{
		// set Thread Policy for Apps if we use version JDK > 9
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		// Initialize url with path is your parameter
		URL url = new URL(urlString);
		// use HttpURLconnection for open connect
		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		InputStream in = urlConnection.getInputStream();
		// Method is importance BitmapFactory.decodeStream to decode stream into Bitmap
		Bitmap bitmapImage = BitmapFactory.decodeStream(in);
		urlConnection.disconnect();
		return bitmapImage;		
	}
	 /** Creates a View to show information about the image referenced by urlString. 
     *  Either creates an ImageView that shows the image, or creates a TextView 
     *  that shows an error message.
     */
	public static View viewForImage(String urlString, Context context){
		Bitmap bitmapImage = null;
		String errorMess = "";
		try {
			bitmapImage = BitmapUtils.bitmapFromUrl(urlString);
		} catch (MalformedURLException e) {
			errorMess = "Malformed URL " + urlString;
			e.printStackTrace();
		} catch (IOException e) {
			errorMess = "Error downloadung image : " + e.getMessage();
			e.printStackTrace();
		}

		if(bitmapImage != null){
			ImageView imgDownLoad = new ImageView(context);
			imgDownLoad.setImageBitmap(bitmapImage);
			imgDownLoad.setPadding(5, 5, 5, 5);
			return imgDownLoad;
		}else{
			TextView txtMess = new TextView(context);
			txtMess.setText(errorMess);
			return txtMess;
		}
	}
}

Layout của chúng ta

</pre>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/main_layout"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".DownLoadImage"
 android:layout_gravity="center">

<TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="URL"
 android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
 android:id="@+id/editUrl"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:ems="10"
 android:inputType="textMultiLine" >

<requestFocus />
 </EditText>

<Button
 android:id="@+id/btnDownload"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Display Image"
 android:onClick="downLoadImage"/>

</LinearLayout>
<pre>

Class Main nè :DownLoadImage.java

package com.thaihoanghai.image;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.thaihoanghai.multithread.R;

public class DownLoadImage extends Activity {
	private EditText mEditUrl;
	private LinearLayout mMainLayout;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_down_load_image);

		setData();
		mEditUrl.setText("http://me.truyennganhay.net/attachment/201205/6/4075_13362876178QnN.jpg");
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.activity_down_load_image, menu);
 return true;
 }

 private void setData(){
 mEditUrl = (EditText) findViewById(R.id.editUrl);
 mMainLayout = (LinearLayout) findViewById(R.id.main_layout);
 }

 public void downLoadImage(View btnView){

 String urlString = mEditUrl.getText().toString().trim();
 View myViewDownLoad = BitmapUtils.viewForImage(urlString, this);

 mMainLayout.addView(myViewDownLoad);
 }

}

OK các bạn có thể tận hưởng rồi. Chúc các bạn beginner thành công =]]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: