[置顶] android从图库(gallery)选择一张图片
16lz
2021-01-23
在android编程中,有时我们可能会有这样的需求,从图库里选择一张图片作为头像
这时,我们就需要从我们的应用中去激活系统的图库应用,并选择一张图片
这个接口android已经为我们提供
我们先来看一下android图库的系统源码,打开android源码_home\packages\apps,在里边我们找到gallery文件夹,即为图库的源码
打开后,我们先打开清单文件,在里边找到这样一段代码
<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”关键字,我们发现这样一段代码
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路径和图片缩略图返回给我们的应用
根据上边的代码,我们就可以来编写实现从图库获取图片的功能了
public class MainActivity extends Activity {private ImageView iv_image;@Overrideprotected 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);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {if (data != null) {// 得到图片的全路径Uri uri = data.getData();// 通过路径加载图片//这里省去了图片缩放操作,如果图片过大,可能会导致内存泄漏//图片缩放的实现,请看:http://blog.csdn.net/reality_jie_blog/article/details/16891095this.iv_image.setImageURI(uri);// 获取图片的缩略图,可能为空!// Bitmap bitmap = data.getParcelableExtra("data");// this.iv_image.setImageBitmap(bitmap);}super.onActivityResult(requestCode, resultCode, data);}}简单的布局文件
<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>
更多相关文章
- 【Android 内存优化】Android 工程中使用 libjpeg-turbo 压缩图
- 集成Android 科大讯飞免费在线语音合成播报功能(附源码)
- Android中关于Volley的使用(四)利用NetworkImageView来加载图片
- Android之rild进程启动源码分析
- Android应用系列:仿MIUI的Toast动画效果实现(有图有源码)
- Android中网络图片的异步加载
- Android拍照调用系统相册仿微信封装总结,治疗各种崩溃,图片横竖