Android实现调用摄像头拍照与视频功能

Android实现调用摄像头拍照与视频功能,第1张

概述应用场景:在Android开发过程中,有时需要调用手机自身设备的功能,上篇文章主要侧重摄像头拍照功能的调用。本篇文章将综合实现拍照与视频的 *** 作。

应用场景:

在AndroID开发过程中,有时需要调用手机自身设备的功能,上篇文章主要侧重摄像头拍照功能的调用。本篇文章将综合实现拍照与视频的 *** 作。

知识点介绍:

该部分请阅读 【Android 调用摄像头功能】

使用方式:

第一步:

新建一个AndroID项目CameraPhotoVedio,包含两个Activity: MainActivity、CameraActivity。

第二步:

activity_main.xml

<relativeLayout 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:background="@drawable/shape_main"  tools:context=".MainActivity" >   <linearLayout androID:layout_height="wrap_content"   androID:layout_margintop="50dp"   androID:layout_wIDth="match_parent"   androID:orIEntation="vertical">   <ImageVIEw androID:layout_height="wrap_content"    androID:layout_wIDth="wrap_content"    androID:layout_gravity="center"    androID:src="@drawable/main"/>  </linearLayout>  <linearLayout androID:layout_height="wrap_content"   androID:layout_margintop="100dp"   androID:layout_wIDth="match_parent"   androID:layout_alignParentBottom="true"   androID:orIEntation="vertical">   <button    androID:ID="@+ID/main_button"    androID:layout_height="50dp"    androID:layout_marginBottom="50dp"    androID:background="@drawable/shape_main"    androID:layout_wIDth="match_parent"    androID:textcolor="#FFFFFF"    androID:text="使用摄像头"/>  </linearLayout> </relativeLayout> 

MainActivity.java

import androID.os.Bundle; import androID.app.Activity; import androID.content.Intent; import androID.vIEw.Menu; import androID.vIEw.VIEw; import androID.vIEw.VIEw.OnClickListener; import androID.Widget.button;  public class MainActivity extends Activity {   private button button; //调用摄像头按钮    @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentVIEw(R.layout.activity_main);   initVIEws();  }   private voID initVIEws() {   button = (button) findVIEwByID(R.ID.main_button);   button.setonClickListener(new OnClickListener() {        @OverrIDe    public voID onClick(VIEw v) {     startActivity(new Intent(getApplicationContext(),CameraActivity.class));    }   });  } } 

activity_camera.xml

<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  xmlns:tools="http://schemas.androID.com/tools"  androID:layout_wIDth="match_parent"  androID:background="#FFFFFF"  androID:layout_height="match_parent"  tools:context=".CameraActivity" >  <SurfaceVIEw   androID:layout_wIDth="match_parent"   androID:layout_height="match_parent"   androID:ID="@+ID/camera_surfacevIEw"/>  <TextVIEw androID:layout_height="wrap_content"   androID:layout_wIDth="wrap_content"   androID:text="计时区域"   androID:ID="@+ID/camera_time"/>  <linearLayout androID:layout_height="wrap_content"   androID:layout_wIDth="match_parent"   androID:layout_alignParentBottom="true"   androID:orIEntation="horizontal">   <button androID:layout_height="30dp"    androID:layout_wIDth="match_parent"    androID:layout_marginBottom="20dp"    androID:layout_weight="1"    androID:background="@drawable/shape_main"    androID:ID="@+ID/camera_photo"    androID:layout_marginleft="5dp"    androID:textcolor="#FFFFFF"    androID:layout_marginRight="5dp"    androID:text="照片摄取"/>   <button androID:layout_height="30dp"    androID:layout_marginBottom="20dp"    androID:layout_wIDth="match_parent"    androID:layout_weight="1"    androID:background="@drawable/shape_main"    androID:ID="@+ID/camera_vedio"    androID:layout_marginleft="5dp"    androID:textcolor="#FFFFFF"    androID:layout_marginRight="5dp"    androID:text="视频摄取"/>  </linearLayout> </relativeLayout> 

CameraActivity.java

import java.io.file; import java.io.fileOutputStream; import java.io.IOException; import java.util.Date;  import com.example.cameraphotovIDeo.utils.FormatUtil;  import androID.graphics.ImageFormat; import androID.harDWare.Camera; import androID.harDWare.Camera.PictureCallback; import androID.media.MediaRecorder; import androID.os.AsyncTask; import androID.os.Bundle; import androID.os.Environment; import androID.os.Handler; import androID.app.Activity; import androID.util.Log; import androID.vIEw.SurfaceHolder; import androID.vIEw.SurfaceHolder.Callback; import androID.vIEw.SurfaceVIEw; import androID.vIEw.VIEw; import androID.vIEw.VIEw.OnClickListener; import androID.Widget.button; import androID.Widget.TextVIEw;  public class CameraActivity extends Activity {   private String tag ="MaHaochen_______CameraActivity";  private SurfaceVIEw surfaceVIEw;  private SurfaceHolder surfaceHolder;  private Camera camera;  private MediaRecorder mediaRecorder;  private button photobutton; //拍照按钮  private button vediobutton; //摄像按钮  private TextVIEw timeTextVIEw;    protected boolean isPrevIEw = false; //摄像区域是否准备良好  private boolean isRecording = true; // true表示没有录像,点击开始;false表示正在录像,点击暂停  private boolean bool;    private int hour = 0;  private int minute = 0;  //计时专用  private int second = 0;    private file mRecVedioPath;  private file mRecAudiofile;    @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentVIEw(R.layout.activity_camera);   initCamera();   initVIEws();  }  //初始化摄像头  private voID initCamera() {   mRecVedioPath = new file(Environment.getExternalStorageDirectory()     .getabsolutePath() + "/mahc/vIDeo/temp/");   if (!mRecVedioPath.exists()) {    mRecVedioPath.mkdirs();   }   surfaceVIEw = (SurfaceVIEw) findVIEwByID(R.ID.camera_surfacevIEw);   SurfaceHolder cameraSurfaceHolder = surfaceVIEw.getHolder();   cameraSurfaceHolder.addCallback(new Callback() {        @OverrIDe    public voID surfaceCreated(SurfaceHolder holder) {     try {     camera = Camera.open();     //设置Camera的角度/方向     camera.setdisplayOrIEntation(90);     Camera.Parameters parameters = camera.getParameters();     parameters.setPrevIEwFrameRate(5); // 每秒5帧     parameters.setPictureFormat(ImageFormat.JPEG);// 设置照片的输出格式     parameters.set("jpeg-quality",85);// 照片质量     camera.setParameters(parameters);     camera.setPrevIEwdisplay(holder);     isPrevIEw = true;     camera.startPrevIEw();     } catch (IOException e) {      e.@R_502_1715@();     }     surfaceHolder = holder;    }        @OverrIDe    public voID surfaceChanged(SurfaceHolder holder,int format,int wIDth,int height) {     surfaceHolder = holder;    }        @OverrIDe    public voID surfaceDestroyed(SurfaceHolder holder) {     if (camera != null) {      if (isPrevIEw) {       camera.stopPrevIEw();       isPrevIEw = false;      }      camera.release();      camera = null; // 记得释放Camera     }     surfaceVIEw = null;     surfaceHolder = null;     mediaRecorder = null;    }   });   //开发时建议设置   //This method was deprecated in API level 11. this is ignored,this value is set automatically when needed.   cameraSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  }    //初始化视图组件  private voID initVIEws() {   timeTextVIEw = (TextVIEw) findVIEwByID(R.ID.camera_time);   timeTextVIEw.setVisibility(VIEw.GONE);   photobutton = (button) findVIEwByID(R.ID.camera_photo);   vediobutton = (button) findVIEwByID(R.ID.camera_vedio);   buttonOnClickListener onClickListener = new buttonOnClickListener();   photobutton.setonClickListener(onClickListener);   vediobutton.setonClickListener(onClickListener);  }    class buttonOnClickListener implements OnClickListener{    @OverrIDe   public voID onClick(VIEw v) {    switch (v.getID()) {    case R.ID.camera_vedio:     //点击开始录像     if(isRecording){      if (isPrevIEw) {       camera.stopPrevIEw();       camera.release();       camera = null;      }      second = 0;      minute = 0;      hour = 0;      bool = true;      if(null==mediaRecorder){       mediaRecorder = new MediaRecorder();      }else {       mediaRecorder.reset();      }      //表面设置显示记录媒体(视频)的预览      mediaRecorder.setPrevIEwdisplay(surfaceHolder.getSurface());      //开始捕捉和编码数据到setoutputfile(指定的文件)      mediaRecorder.setVIDeoSource(MediaRecorder.VIDeoSource.CAMERA);      //设置用于录制的音源      mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);      //设置在录制过程中产生的输出文件的格式      mediaRecorder.setoutputFormat(MediaRecorder.OutputFormat.THREE_GPP);      //设置视频编码器,用于录制      mediaRecorder.setVIDeoEncoder(MediaRecorder.VIDeoEncoder.H264);      //设置audio的编码格式      mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);      //设置要捕获的视频的宽度和高度      mediaRecorder.setVIDeoSize(320,240);      // 设置要捕获的视频帧速率      mediaRecorder.setVIDeoFrameRate(15);      try {       mRecAudiofile = file.createTempfile("Vedio",".3gp",mRecVedioPath);      } catch (IOException e) {       e.@R_502_1715@();      }      mediaRecorder.setoutputfile(mRecAudiofile.getabsolutePath());      try {       mediaRecorder.prepare();       timeTextVIEw.setVisibility(VIEw.VISIBLE);       handler.postDelayed(task,1000);       mediaRecorder.start();      } catch (Exception e) {       e.@R_502_1715@();      }      isRecording = !isRecording;      Log.e(tag,"=====开始录制视频=====");     }else {      //点击停止录像      bool = false;      mediaRecorder.stop();      timeTextVIEw.setText(FormatUtil.format(hour)+":"+FormatUtil.format(minute)+":"+ FormatUtil.format(second));      mediaRecorder.release();      mediaRecorder = null;      FormatUtil.vIDeoRename(mRecAudiofile);      Log.e(tag,"=====录制完成,已保存=====");      isRecording = !isRecording;      try {       camera = Camera.open();       Camera.Parameters parameters = camera.getParameters(); //      parameters.setPrevIEwFrameRate(5); // 每秒5帧       parameters.setPictureFormat(ImageFormat.JPEG);// 设置照片的输出格式       parameters.set("jpeg-quality",85);// 照片质量       camera.setParameters(parameters);       camera.setPrevIEwdisplay(surfaceHolder);       camera.startPrevIEw();       isPrevIEw = true;      } catch (Exception e) {       e.@R_502_1715@();      }     }     break;     case R.ID.camera_photo:     if (mediaRecorder != null) {      try {       bool = false;       mediaRecorder.stop();       timeTextVIEw.setText(FormatUtil.format(hour) + ":" + FormatUtil.format(minute) + ":"         + FormatUtil.format(second));       mediaRecorder.release();       mediaRecorder = null;       FormatUtil.vIDeoRename(mRecAudiofile);      } catch (Exception e) {       e.@R_502_1715@();      }      isRecording = !isRecording;      Log.e(tag,"=====录制完成,已保存=====");      try {       camera = Camera.open();       Camera.Parameters parameters = camera.getParameters(); //      parameters.setPrevIEwFrameRate(5); // 每秒5帧       parameters.setPictureFormat(ImageFormat.JPEG);// 设置照片的输出格式       parameters.set("jpeg-quality",85);// 照片质量       camera.setParameters(parameters);       camera.setPrevIEwdisplay(surfaceHolder);       camera.startPrevIEw();       isPrevIEw = true;      } catch (Exception e) {       e.@R_502_1715@();      }     }     if (camera != null) {      camera.autoFocus(null);      camera.takePicture(null,null,new PictureCallback() {       @OverrIDe       public voID onPictureTaken(byte[] data,Camera camera) {        new SavePictureTask().execute(data);        camera.startPrevIEw();        Log.e(tag,"=====拍照成功=====");       }      }); // 拍照     }     break;    default:     break;    }   }  }  /*   * 定时器设置,实现计时   */  private Handler handler = new Handler();  private Runnable task = new Runnable() {   public voID run() {    if (bool) {     handler.postDelayed(this,1000);     second++;     if (second >= 60) {      minute++;      second = second % 60;     }     if (minute >= 60) {      hour++;      minute = minute % 60;     }     timeTextVIEw.setText(FormatUtil.format(hour) + ":" + FormatUtil.format(minute) + ":"       + FormatUtil.format(second));    }   }  };        class SavePictureTask extends AsyncTask<byte[],String,String> {   @OverrIDe   protected String doInBackground(byte[]... params) {    String path = Environment.getExternalStorageDirectory()      .getabsolutePath() + "/mahc/image";    file out = new file(path);    if (!out.exists()) {     out.mkdirs();    }    file picture = new file(path+"/"+new Date().getTime()+".jpg");    try {     fileOutputStream fos = new fileOutputStream(picture.getPath());     fos.write(params[0]);     fos.close();    } catch (Exception e) {     e.@R_502_1715@();    }    Log.e(tag,"=====照片保存完成=====");    CameraActivity.this.finish();    return null;   }  } } 

第三步:该项目需要一个工具类FormatUtil.java

import java.io.file; import java.text.SimpleDateFormat; import java.util.Date;  import androID.os.Environment;  public class FormatUtil {   /**   * 将缓存文件夹的数据转存到vedio文件下   * @param recAudiofile   */  public static voID vIDeoRename(file recAudiofile) {   String path = Environment.getExternalStorageDirectory()     .getabsolutePath()+ "/mahc/vIDeo/"+ "0" + "/";   String filename = new SimpleDateFormat("yyyyMMddHHmmss")     .format(new Date()) + ".3gp";   file out = new file(path);   if (!out.exists()) {    out.mkdirs();   }   out = new file(path,filename);   if (recAudiofile.exists())    recAudiofile.renameTo(out);  }    /**   * 用以计时 *** 作的相关方法   * @param num   * @return   */  public static String format(int num){   String s = num + "";   if (s.length() == 1) {    s = "0" + s;   }   return s;  } } 

第四步:本项目需要处理界面的背景样式和按钮的背景,所以需要在res/drawable文件新建shape_main.xml。

<?xml version="1.0" enCoding="utf-8"?> <shape xmlns:androID="http://schemas.androID.com/apk/res/androID">  <gradIEnt   androID:startcolor="#FFCC99"   androID:endcolor="#99CC66"   androID:centercolor="#0066CC"   androID:angle="45" /> </shape> 

页面效果:

效果截图

下载地址:Android实现调用摄像头拍照与视频功能

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

您可能感兴趣的文章:Android实现摄像头拍照功能Android调用摄像头拍照开发教程Android实现调用摄像头进行拍照功能android开发之调用手机的摄像头使用MediaRecorder录像并播放Android开发教程之调用摄像头功能的方法详解Android中判断是否有前置摄像头、后置摄像头的方法Android判断用户是否允许了摄像头权限实例代码Android实现调用摄像头Android调用前后摄像头同时工作实例代码Android 开发随手笔记之使用摄像头拍照 总结

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

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

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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存