当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 开发照相功能实例详解

Android 开发照相功能实例详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

android 照相

在android中,照相功能系统已经提供,在app中可以直接使用。当手机从android play里面下载有照相功能的应用时, 会判断手机是否支持。不支持,不给予下载。

照相有几个步骤:

1. 声明权限
2. 使用camera照相
3. 显示图片

1. 声明权限

在manifest里面声明使用camera:

<uses-feature android:name="android.hardware.camera" /> 

2. 使用camera照相

在activity中,调用camera应用

private void dispatchtakepictureintent(int actioncode) { 
  intent takepictureintent = new intent(mediastore.action_image_capture); 
  startactivityforresult(takepictureintent, actioncode); 
} 

3. 显示图片

在使用camera照相成功之后,会返回回来,要显示图片就必须先获取图片,然后显示出来。

在onactivityresult方法中取得

 protected void onactivityresult(int requestcode, int resultcode, intent data) { 
    switch (requestcode) { 
    bundle extras = intent.getextras(); 
    bitmap mimagebitmap = (bitmap) extras.get("data"); 
    mimageview.setimagebitmap(mimagebitmap); 

想要保存图片到制定目录,启动camera应用时,需要指定文件

intent takepictureintent = new intent(mediastore.action_image_capture); 
file f = null; 
       
      try { 
        f = setupphotofile();  
        takepictureintent.putextra(mediastore.extra_output, uri.fromfile(f)); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
        f = null; 
      } 

private file createimagefile() throws ioexception { 
    // create an image file name 
    string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date()); 
    string imagefilename = "img_"+ timestamp + "_"; 
    file albumf = getalbumdir(); 
    file imagef = file.createtempfile(imagefilename, "jpg", albumf); 
    return imagef; 
  } 
 
 
  private file setupphotofile() throws ioexception { 
     
    file f = createimagefile(); 
    mcurrentphotopath = f.getabsolutepath(); 
     
    return f; 
  } 
private file getalbumdir() { 
    file storagedir = null; 
 
 
    if (environment.media_mounted.equals(environment.getexternalstoragestate())) { 
       
      storagedir = malbumstoragedirfactory.getalbumstoragedir(getalbumname()); 
 
 
      if (storagedir != null) { 
        if (! storagedir.mkdirs()) { 
          if (! storagedir.exists()){ 
            log.d("camerasample", "failed to create directory"); 
            return null; 
          } 
        } 
      } 
       
    } else { 
      log.v(getstring(r.string.app_name), "external storage is not mounted read/write."); 
    } 
     
    return storagedir; 
  } 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网