Android调用摄像头拍照开发教程

Android调用摄像头拍照开发教程,第1张

概述现在很多应用中都会要求用户上传一张图片来作为头像,首先我在这接收使用相机拍照和在相册中选择图片。接下来先上效果图:

现在很多应用中都会要求用户上传一张图片来作为头像,首先我在这接收使用相机拍照和在相册中选择图片。接下来先上效果图:

 

接下来看代码:

1、布局文件:

<?xml version="1.0" enCoding="utf-8"?><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="com.gyq.cameraalbumtest.MainActivity">  <button    androID:ID="@+ID/btn_take_photo"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"    androID:text="take photo"/>  <button    androID:ID="@+ID/choose_from_album"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"    androID:text="choose from album"/>  <ImageVIEw    androID:ID="@+ID/iv_picture"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:layout_gravity="center_horizontal"/></linearLayout>

2、MainActivity.java逻辑代码:

package com.gyq.cameraalbumtest;import androID.Manifest;import androID.annotation.TargetAPI;import androID.content.ContentUris;import androID.content.Intent;import androID.content.pm.PackageManager;import androID.database.Cursor;import androID.graphics.Bitmap;import androID.graphics.BitmapFactory;import androID.net.Uri;import androID.os.Build;import androID.os.Bundle;import androID.provIDer.documentsContract;import androID.provIDer.MediaStore;import androID.support.annotation.NonNull;import androID.support.v4.app.ActivityCompat;import androID.support.v4.content.ContextCompat;import androID.support.v4.content.fileProvIDer;import androID.support.v7.app.AppCompatActivity;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.ImageVIEw;import androID.Widget.Toast;import java.io.file;public class MainActivity extends AppCompatActivity {  public static final int TAKE_PHOTO = 1;  public static final int CHOOSE_PHOTO = 2;  private button mTakePhoto,mChoosePhoto;  private ImageVIEw picture;  private Uri imageUri;  @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);    mTakePhoto = (button) findVIEwByID(R.ID.btn_take_photo);    mChoosePhoto = (button) findVIEwByID(R.ID.choose_from_album);    picture = (ImageVIEw) findVIEwByID(R.ID.iv_picture);    mTakePhoto.setonClickListener(new VIEw.OnClickListener() {      @OverrIDe      public voID onClick(VIEw v) {        //创建file对象,用于存储拍照后的图片;        file outputimage = new file(getExternalCacheDir(),"output_image.jpg");        try {          if (outputimage.exists()) {            outputimage.delete();          }          outputimage.createNewfile();        } catch (Exception e) {          e.printstacktrace();        }        if (Build.VERSION.SDK_INT >= 24) {          imageUri = fileProvIDer.getUriForfile(MainActivity.this,"com.gyq.cameraalbumtest.fileprovIDer",outputimage);        } else {          imageUri = Uri.fromfile(outputimage);        }        //启动相机程序        Intent intent = new Intent("androID.media.action.IMAGE_CAPTURE");        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);        startActivityForResult(intent,TAKE_PHOTO);      }    });    mChoosePhoto.setonClickListener(new VIEw.OnClickListener() {      @OverrIDe      public voID onClick(VIEw v) {        if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {          ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);        } else {          openAlbum();        }      }    });  }  //打开相册  private voID openAlbum() {    Intent intent = new Intent("androID.intent.action.GET_CONTENT");    intent.setType("image/*");    startActivityForResult(intent,CHOOSE_PHOTO);  }  @OverrIDe  public voID onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {    switch (requestCode) {      case 1:        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {          openAlbum();        } else {          Toast.makeText(this,"you denIEd the permission",Toast.LENGTH_SHORT).show();        }        break;    }  }  @OverrIDe  protected voID onActivityResult(int requestCode,int resultCode,Intent data) {    switch (requestCode) {      case TAKE_PHOTO:        if (resultCode == RESulT_OK) {          try {            Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openinputStream(imageUri));            picture.setimageBitmap(bm);          } catch (Exception e) {            e.printstacktrace();          }        }        break;      case CHOOSE_PHOTO:        if (resultCode == RESulT_OK) {          if (Build.VERSION.SDK_INT >= 19) { //4.4及以上的系统使用这个方法处理图片;            handleImageOnKitKat(data);          } else {            handleImageBeforeKitKat(data); //4.4及以下的系统使用这个方法处理图片          }        }      default:        break;    }  }  private voID handleImageBeforeKitKat(Intent data) {    Uri uri = data.getData();    String imagePath = getimagePath(uri,null);    displayImage(imagePath);  }  private String getimagePath(Uri uri,String selection) {    String path = null;    //通过Uri和selection来获取真实的图片路径    Cursor cursor = getContentResolver().query(uri,null,selection,null);    if (cursor != null) {      if (cursor.movetoFirst()) {        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));      }      cursor.close();    }    return path;  }  private voID displayImage(String imagePath) {    if (imagePath != null) {      Bitmap bitmap = BitmapFactory.decodefile(imagePath);      picture.setimageBitmap(bitmap);    } else {      Toast.makeText(this,"Failed to get image",Toast.LENGTH_SHORT).show();    }  }  /**   * 4.4及以上的系统使用这个方法处理图片   *   * @param data   */  @TargetAPI(19)  private voID handleImageOnKitKat(Intent data) {    String imagePath = null;    Uri uri = data.getData();    if (documentsContract.isdocumentUri(this,uri)) {      //如果document类型的Uri,则通过document来处理      String docID = documentsContract.getdocumentID(uri);      if ("com.androID.provIDers.media.documents".equals(uri.getAuthority())) {        String ID = docID.split(":")[1];   //解析出数字格式的ID        String selection = MediaStore.Images.Media._ID + "=" + ID;        imagePath = getimagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);      } else if ("com.androID.provIDers.downloads.documents".equals(uri.getAuthority())) {        Uri contentUri = ContentUris.withAppendedID(Uri.parse("content://downloads/piblic_downloads"),Long.valueOf(docID));        imagePath = getimagePath(contentUri,null);      }    } else if ("content".equalsIgnoreCase(uri.getScheme())) {      //如果是content类型的uri,则使用普通方式使用      imagePath = getimagePath(uri,null);    } else if ("file".equalsIgnoreCase(uri.getScheme())) {      //如果是file类型的uri,直接获取路径即可      imagePath = uri.getPath();    }    displayImage(imagePath);  }}

3、清单文件:

<?xml version="1.0" enCoding="utf-8"?><manifest xmlns:androID="http://schemas.androID.com/apk/res/androID"  package="com.gyq.cameraalbumtest">  <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/>  <application    androID:allowBackup="true"    androID:icon="@mipmap/ic_launcher"    androID:label="@string/app_name"    androID:supportsRtl="true"    androID:theme="@style/Apptheme">    <activity androID:name=".MainActivity">      <intent-filter>        <action androID:name="androID.intent.action.MAIN" />        <category androID:name="androID.intent.category.LAUNCHER" />      </intent-filter>    </activity>    <provIDer      androID:authoritIEs="com.gyq.cameraalbumtest.fileprovIDer"      androID:name="androID.support.v4.content.fileProvIDer"      androID:exported="false"      androID:grantUriPermissions="true">      <Meta-data androID:name="androID.support.file_PROVIDER_PATHS"            androID:resource="@xml/file_paths"/>    </provIDer>  </application></manifest>

4、xml文件夹中的文件

<?xml version = "1.0" enCoding = "utf-8"?> <paths xmlns:androID = "http://schemas.androID.com/apk/res/androID">   <external-path name = "my_images" path = ""></external-path> </paths>

OK,完成收工。请继续关注我的博客。谢谢!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

您可能感兴趣的文章:Android 实现调用系统照相机拍照和录像的功能Android 调用系统照相机拍照和录像Android自定义照相机倒计时拍照Android调用系统摄像头拍照并显示在ImageView上Android实现调用摄像头拍照与视频功能Android实现摄像头拍照功能Android实现调用摄像头进行拍照功能Android实现拍照、选择图片并裁剪图片功能Android调用系统照相机拍照与摄像的方法 总结

以上是内存溢出为你收集整理的Android调用摄像头拍照开发教程全部内容,希望文章能够帮你解决Android调用摄像头拍照开发教程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1142798.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存