Android中實現呼叫攝像頭拍照並顯示在ImageView中
阿新 • • 發佈:2020-12-01
場景
點選拍照按鈕呼叫系統攝像機進行拍照,並將拍的照片顯示在ImageView中。
注:
部落格:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程式猿
獲取程式設計相關電子書、教程推送與免費下載。
實現
新建一個Activity,設計其佈局如下
佈局xml檔案為
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".CameraActivity"> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="啟動攝像頭" /> <ImageView android:id="@+id/iv_camera" android:layout_width="350dp" android:layout_height="350dp" android:layout_gravity="center" android:layout_marginTop="20dp" /> </LinearLayout>
然後在對應的Activity中,通過指定Action的Intent來呼叫系統攝像頭,並採用帶返回結果的方式啟動Activity,
然後在重寫的獲取Activity返回結果的方法中,判斷請求碼與上面自定義的常量一致並且請求結果為OK
那麼通過將data強轉為Bitmap並給ImageView設定資料來源進行顯示
package com.badao.androidstudy; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class CameraActivity extends AppCompatActivity { private Button btnCamera; private ImageView imageView; private final int CAMERA_REQUEST = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); initView(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case CAMERA_REQUEST: if (resultCode == RESULT_OK) { Bitmap bitmap = (Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(bitmap); } break; } } public void initView(){ imageView = findViewById(R.id.iv_camera); btnCamera = findViewById(R.id.button); btnCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent,CAMERA_REQUEST); } }); } }