当前位置: 移动技术网 > IT编程>移动开发>Android > android 照相功能的简单实例

android 照相功能的简单实例

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

云梦股票论坛,2014大崩溃 胡乔英,惘然缘

在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方法中取得

复制代码 代码如下:

<pre class=java name="code">@override 
    protected void onactivityresult(int requestcode, int resultcode, intent data) { 
        switch (requestcode) { 
        bundle extras = intent.getextras(); 
        bitmap mimagebitmap = (bitmap) extras.get("data"); 
        mimageview.setimagebitmap(mimagebitmap); 
}</pre> 
<pre></pre> 
<pre></pre> 


想要保存图片到制定目录,启动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; 
    } 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网