1. 程式人生 > >獲取網路上的圖片,並顯示在介面上的簡單實現

獲取網路上的圖片,並顯示在介面上的簡單實現

佈局檔案如下:

<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"
tools:context=".MainActivity">
    <EditText
android:id="@+id/et_main_netpass"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="請輸入地址" android:text="https://www.baidu.com/img/bd_logo1.png"/> <Button android:id="@+id/bt_main_see" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="檢視圖片"/> <ImageView
android:id="@+id/iv_main_showimage" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>

在AndroidManifest檔案中新增網路訪問許可權;

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

實現程式碼如下:

package cn.test.ning.netimageview;
import android.app.Activity
; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Base64; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends Activity { private static final int UPDATE = 0; private EditText et_main_netpass; private ImageView iv_main_showimage; private Button bt_main_see; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE: { Bitmap bitmap = (Bitmap) msg.obj; iv_main_showimage.setImageBitmap(bitmap); break; } default: break; } } }; private void initView() { setContentView(R.layout.activity_main); et_main_netpass = (EditText) this.findViewById(R.id.et_main_netpass); iv_main_showimage = (ImageView) this.findViewById(R.id.iv_main_showimage); bt_main_see = (Button) this.findViewById(R.id.bt_main_see); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); initEvent(); } private void initEvent() { bt_main_see.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String path = et_main_netpass.getText().toString().trim(); if (TextUtils.isEmpty(path)) {//檢測路徑是否合法 Toast.makeText(MainActivity.this, "路徑為空", Toast.LENGTH_SHORT).show(); return; } else { //從快取中取出圖片,並顯示在介面中 File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(), Base64.DEFAULT)); if (file.exists() && file.length() > 0) { Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); iv_main_showimage.setImageBitmap(bitmap); Toast.makeText(MainActivity.this, "get image form cache", Toast.LENGTH_SHORT).show(); } else { new Thread() { @Override public void run() {//在子執行緒中訪問網路,並快取圖片資源 try { //申明訪問的路徑 URL url = new URL(path); //通過路徑,得到連結 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //設定連結方式 connection.setRequestMethod("GET"); //設定連結超時時間 connection.setConnectTimeout(5000); //設定寫入超時時間 connection.setReadTimeout(5000); //獲取請求響應碼 int code = connection.getResponseCode(); if (200 == code) { //獲取請求返回的位元組流 InputStream inputStream = connection.getInputStream(); File file = new File(MainActivity.this.getCacheDir(), Base64.encodeToString(path.getBytes(), Base64.DEFAULT)); byte[] buffer = new byte[1024]; int len = 0; FileOutputStream fos = new FileOutputStream(file); while ((len = inputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); inputStream.close(); Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); //Bitmap bitmap = BitmapFactory.decodeStream(inputStream); //iv_main_showimage.setImageBitmap(bitmap); Message message = Message.obtain(); message.what = UPDATE; message.obj = bitmap; mHandler.sendMessage(message); } else { Toast.makeText(MainActivity.this, "reqeust is fail", Toast.LENGTH_SHORT).show(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { } } }.start(); } } } }); } }