打开手机图库和打开照相机返回选中的图片简单小运用

打开手机图库和打开照相机返回选中的图片简单小运用android

功能:界面有2个按钮 一、选择照片 二、拍摄照片 把选择的照片或者拍摄的照片显示在该页面ide

//1 -- 布局界面 activity_main.xml
代码布局

<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" >this

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选择图片"
        android:onClick="choose_image"
         />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="拍摄照片"
        android:onClick="camere"
         />code

</LinearLayout>
-------------------------xml

//2 -- MainActivity 类对象

代码事件

public class MainActivity extends Activity {
private ImageView image;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  image = (ImageView) this.findViewById(R.id.imageview);
 }
 //打开图库 选择 图片 按钮 事件 监听
 public void choose_image(View view){
  Intent intent = new Intent();
  //打开图库
  intent.setAction(intent.ACTION_PICK);
//设置图片的类型 -- 所有类型/*
  intent.setType("image/*");
  int requestCode = 1;
//用带返回结果的启动跳转方法
  startActivityForResult(intent, requestCode );
 }
 
 //拍摄 照片 按钮 事件 监听
 public void camere(View view){
  Intent intent = new Intent();
  //打开相机
  intent.setAction("android.media.action.IMAGE_CAPTURE");
  int requestCode = 2;
  startActivityForResult(intent, requestCode );
 }
 @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if(data == null || resultCode !=Activity.RESULT_OK){
    Toast.makeText(this, "没有选择图片!", Toast.LENGTH_SHORT).show();
    return ;
   }
   if(requestCode == 1){
    //用getData方法 获取 从图库 返回来的 数据
    Uri uri = data.getData();
    //用 ContentResolver 解析器 解析返回来的 数据
    ContentResolver cr = getContentResolver();
    try {
     //把返回来的数据 给 openInputStream 进行 解析
     InputStream is = cr.openInputStream(uri);
     //解析工厂 对流 is 对象 进行 解析
     Bitmap bitmap = BitmapFactory.decodeStream(is);
     image.setImageBitmap(bitmap);
    } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if(requestCode == 2){
    //获取 拍摄的数据 -- 方法getParcelableExtra
    Bitmap bitmap = data.getParcelableExtra("data");
    image.setImageBitmap(bitmap);
   }
  }
}图片

相关文章
相关标签/搜索