在android编程中,有时我们可能会有这样的需求,从图库里选择一张图片作为头像
这时,我们就需要从我们的应用中去激活系统的图库应用,并选择一张图片
这个接口android已经为我们提供
我们先来看一下android图库的系统源码,打开android源码_home\packages\apps,在里边我们找到gallery文件夹,即为图库的源码
打开后,我们先打开清单文件,在里边找到这样一段代码
[html]
<activity android:name="com.android.camera.ImageGallery"
android:label="@string/gallery_label"
android:configChanges="orientation|keyboardHidden"
android:icon="@drawable/ic_launcher_gallery">
.......
<intent-filter>
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
</intent-filter>
.......
</activity>
从上边的意图过滤器我们可以发现,我们可以通过一个叫android.intent.action.PICK的action来激活图库并选择图片或是视频
为了知道图库应用给我们返回的key值是什么,我们还需到com.android.camera.ImageGallery类去看一下源码
在src目录下找到该类并打开,我们在里边搜“setResult”关键字,我们发现这样一段代码
[java]
else {
Intent result = new Intent(null, img.fullSizeImageUri());
if (myExtras != null && myExtras.getBoolean("return-data")) {
// The size of a transaction should be below 100K.
Bitmap bitmap = img.fullSizeBitmap(
IImage.UNCONSTRAINED, 100 * 1024);
if (bitmap != null) {
result.putExtra("data", bitmap);
}
}
setResult(RESULT_OK, result);
finish();
我们发现,图库应用会将图片的URL路径和图片缩略图返回给我们的应用
根据上边的代码,我们就可以来编写实现从图库获取图片的功能了
[java]
public class MainActivity extends Activity {
private ImageView iv_image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.iv_image = (ImageView) this.findViewById(R.id.iv_image);
}
public void load(View view) {
// 激活系统图库,选择一张图片
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
// 得到图片的全路径
Uri uri = data.getData();
// 通过路径加载图片
//这里省去了图片缩放操作,如果图片过大,可能会导致内存泄漏
//图片缩放的实现,请看:http://blog.csdn.net/reality_jie_blog/article/details/16891095
this.iv_image.setImageURI(uri);
// 获取图片的缩略图,可能为空!
// Bitmap bitmap = data.getParcelableExtra("data");
// this.iv_image.setImageBitmap(bitmap);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
简单的布局文件
[html]
<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" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="load"
android:text="获取图库图片" />
<ImageView
android:id="@+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>