应用在获取图片时可以从两个地方获取:本地图片资源以及网络图片资源。先面分别介绍一下这两种获取的方式。
网络获取图片资源
主要是通过图片资源的URL进行网络链接,然后读取数据流,获取Bitmap对象
代码如下:
public class AsyncTaskTest extends Activity {
private static String photohttp = "http://d.hiphotos.baidu.com/album/w%3D2048/sign=f3bdf562faf2b211e42e824efeb86438/8435e5dde71190ef954301cecf1b9d16fdfa6063.jpg";
private ImageView mIV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.async_task_test);
loadPhtot();
mIV = (ImageView) findViewById(R.id.imageview);
}
private void loadPhtot() {
new LoadPhotoAsyncTask().execute(photohttp);
}
private class LoadPhotoAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected void onPostExecute(Bitmap result) {
mIV.setImageBitmap(result);
}
@Override
protected Bitmap doInBackground(String... params) {
return loadImageFromNetwork(params[0]);
}
private Bitmap loadImageFromNetwork(String string) {
Bitmap bitmap = null;
URL url;
try {
url = new URL(string);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6000);
conn.setDoInput(true);
conn.setUseCaches(false);
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
conn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
}
}
资源文件async_task_test.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ImageView>
</LinearLayout>
相关文章阅读:
点击打开链接
本机内部图片资源的获取
主要通过Uri获取图片的文件流。
待续~~~~~~