小demo一个,今天用到了,那么就分享给大家,希望对大家有所收获
先上效果图:
示例源码:
1.添加访问sd卡权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2.源码
package com.zengtao.demo; import java.io.FileNotFoundException; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends ActionBarActivity { private Button bt; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.id.bt); iv = (ImageView) findViewById(R.id.iv); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, 1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == RESULT_OK) { if (data != null) { Uri uri = data.getData(); ContentResolver cr = this.getContentResolver(); try { Bitmap bitmap = BitmapFactory.decodeStream(cr .openInputStream(uri)); iv.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } super.onActivityResult(requestCode, resultCode, data); } }
以上便是完成打开图库,并将选择的图片返回给现在所用的应用,当然其实这里面还是有一点缺陷,那就是照片太大的情况下,需要改正,在图库中拿到的图片需要进行一个处理之后也就是缩略之后才能不会出现异常,关于这一点,相信其他大神里面会有提到。
原文地址:http://blog.csdn.net/u011546655/article/details/43562021