Android基礎入門教程——9.3 使用Camera拍照

來源:互聯網
上載者:User

Android基礎入門教程——9.3 使用Camera拍照
Android基礎入門教程——9.3 使用Camera拍照

標籤(空格分隔): Android基礎入門教程

本節引言

本節給大家帶來的是Android中Camera的使用,簡單點說就是拍照咯,無非兩種,
1.調用系統內建相機拍照,然後擷取拍照後的圖片
2.要麼自己寫個拍照頁面
本節我們來寫兩個簡單的例子體驗下上面的這兩種情況~

1.調用系統內建Carema

我們只需下面一席話語,即可調用系統相機,相機拍照後會返回一個intent給onActivityResult。
intent的extra部分包含一個編碼過的Bitmap~

Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);startActivityForResult(it,Activity.DEFAULT_KEYS_DIALER);//重寫onActivityResult方法    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        if(requestCode == Activity.RESULT_OK){            Bundle bundle = data.getExtras();            Bitmap bitmap = (Bitmap) bundle.get(data);            img_show.setImageBitmap(bitmap);        }}        

運行:

這模糊的AV畫質…畢竟是編碼過後的Bitmap,對了,拍完的圖片是不會儲存到本地的,
我們可以自己寫代碼把圖片儲存到我們的SD卡裡,然後再顯示,這樣的圖片會清晰很多,
嗯,我們寫代碼來試下~

//定義一個儲存圖片的File變數private File currentImageFile = null;//在按鈕點擊事件處寫上這些東西,這些是在SD卡建立圖片檔案的:            @Override            public void onClick(View v) {                File dir = new File(Environment.getExternalStorageDirectory(),pictures);                if(dir.exists()){                    dir.mkdirs();                }                currentImageFile = new File(dir,System.currentTimeMillis() + .jpg);                if(!currentImageFile.exists()){                    try {                        currentImageFile.createNewFile();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                it.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentImageFile));                startActivityForResult(it, Activity.DEFAULT_KEYS_DIALER);            }//onActivityResult: @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        if (requestCode == Activity.DEFAULT_KEYS_DIALER) {        img_show.setImageURI(Uri.fromFile(currentImageFile));        }}

好的,非常簡單,我們來看下運行結果:

相比起上面那個清晰多了~調用系統內建Carema就是這麼簡單~

2.自己寫一個拍照頁面

這裡我們需要用一個SurfaceView作為我們的預覽介面,使用起來同一非常簡單!

運行:

代碼實現:

布局代碼:activity_main.xml:一個簡單的surfaceView + Button

        

MainActivity.java:

public class MainActivity extends AppCompatActivity {    private SurfaceView sfv_preview;    private Button btn_take;    private Camera camera = null;    private SurfaceHolder.Callback cpHolderCallback = new SurfaceHolder.Callback() {        @Override        public void surfaceCreated(SurfaceHolder holder) {            startPreview();        }        @Override        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {        }        @Override        public void surfaceDestroyed(SurfaceHolder holder) {            stopPreview();        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        bindViews();    }    private void bindViews() {        sfv_preview = (SurfaceView) findViewById(R.id.sfv_preview);        btn_take = (Button) findViewById(R.id.btn_take);        sfv_preview.getHolder().addCallback(cpHolderCallback);        btn_take.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                camera.takePicture(null, null, new Camera.PictureCallback() {                    @Override                    public void onPictureTaken(byte[] data, Camera camera) {                        String path = ;                        if ((path = saveFile(data)) != null) {                            Intent it = new Intent(MainActivity.this, PreviewActivity.class);                            it.putExtra(path, path);                            startActivity(it);                        } else {                            Toast.makeText(MainActivity.this, 儲存照片失敗, Toast.LENGTH_SHORT).show();                        }                    }                });            }        });    }    //儲存臨時檔案的方法    private String saveFile(byte[] bytes){        try {            File file = File.createTempFile(img,);            FileOutputStream fos = new FileOutputStream(file);            fos.write(bytes);            fos.flush();            fos.close();            return file.getAbsolutePath();        } catch (IOException e) {            e.printStackTrace();        }        return ;    }    //開始預覽    private void startPreview(){        camera = Camera.open();        try {            camera.setPreviewDisplay(sfv_preview.getHolder());            camera.setDisplayOrientation(90);   //讓相機旋轉90度            camera.startPreview();        } catch (IOException e) {            e.printStackTrace();        }    }    //停止預覽    private void stopPreview() {        camera.stopPreview();        camera.release();        camera = null;    }}

最後是另外一個PreviewActivity.java,這裡將圖片顯示到介面上而已~

/** * Created by Jay on 2015/11/22 0022. */public class PreviewActivity extends AppCompatActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        ImageView img = new ImageView(this);        String path = getIntent().getStringExtra(path);        if(path != null){            img.setImageURI(Uri.fromFile(new File(path)));        }        setContentView(img);    }}

嗯,都非常簡單哈,別忘了加上許可權:

        

另外,有一點要說的就是假如carema沒有釋放掉的話,那麼下次調用carema就不會報錯,
報錯內容是:java.lang.RuntimeException:fail to connect to camera service
所以,需要對Carema進行release();假如一直報上面的錯誤,請重啟手機~

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.