本文实例讲述了Android开发之加载图片的方法。分享给大家供大家参考。具体分析如下:
加载网络上的图片需要在manifest中配置访问网络的权限,如下:
<uses-permission android:name="android.permission.INTERNET" />
如果不配置这个权限的话,会报错:unknown host exception。
1
2
3
4
5
6
7
8
9
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
|
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<String, Void, Bitmap> {
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);
}
}
}
|
如果是加载本地图片的话,直接来:
1
2
|
ImageView v = (ImageView) findViewById(R.id.imageView1);
v.setImageResource(R.drawable.apic);
|
在使用AsyncTask加载图片的时候可以顺便把图片保存在本地:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
@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程序设计有所帮助。