本文实例讲述了Android开发之加载图片的方法。分享给大家供大家参考。具体分析如下:
加载网络上的图片需要在manifest中配置访问网络的权限,如下:
如果不配置这个权限的话,会报错:unknown host exception。
package com.example.loadimgfromweb; import java.io.InputStream; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.widget.ImageView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView v = (ImageView) findViewById(R.id.imageView1); String url = "http://minimg.hexun.com/i1.hexunimg.cn/2011-11-07/134970028_200x150.jpg"; new DownLoadImage(v).execute(url); } @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_main, menu); return true; } public class DownLoadImage extends AsyncTask上面的例子中使用了AsyncTask来与前端用户界面进行交互。避免加载时间过长,影响界面的交互性。{ ImageView imageView; public DownLoadImage(ImageView imageView) { this.imageView = imageView; } @Override protected Bitmap doInBackground(String... urls) { String url = urls[0]; Bitmap tmpBitmap = null; try { InputStream is = new java.net.URL(url).openStream(); tmpBitmap = BitmapFactory.decodeStream(is); } catch (Exception e) { e.printStackTrace(); } return tmpBitmap; } @Override protected void onPostExecute(Bitmap result) { imageView.setImageBitmap(result); } } }
如果是加载本地图片的话,直接来:
ImageView v = (ImageView) findViewById(R.id.imageView1); v.setImageResource(R.drawable.apic);
在使用AsyncTask加载图片的时候可以顺便把图片保存在本地:
@Override protected Bitmap doInBackground(String... urls) { String url = urls[0]; Bitmap tmpBitmap = null; try { InputStream is = new java.net.URL(url).openStream(); URL u = new URL(url); HttpURLConnection cOnn= (HttpURLConnection) u.openConnection(); Bitmap bitmap = BitmapFactory.decodeStream(is); // 判断是否有内存卡 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // 保存图片到本地 File sdCardDir = Environment.getExternalStorageDirectory(); String fileName = "a.jpg"; String filePath = sdCardDir + "/" + fileName; FileOutputStream fos = new FileOutputStream(filePath); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } // 关闭流 is.close(); conn.disconnect(); return bitmap; } catch (Exception e) { e.printStackTrace(); } return tmpBitmap; }
希望本文所述对大家的Android程序设计有所帮助。