Android Realizes Camera Photographing Function
- 2021-09-05 01:06:28
- OfStack
Application scenario:
In the process of Android development, it is sometimes necessary to call the functions of the mobile phone's own equipment. This paper focuses on the call of the camera photo function.
Introduction of knowledge points:
Permission: To invoke the phone's own device function (camera photo function), make sure that the use of the camera and other related feature have been correctly stated in AndroidManifest. xml.
<!-- Camera permissions -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- Storage permissions SD Card read-write permission -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--Camera Feature Declaration pair camera feature Use of -->
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<!-- Video and recording rights Request Audio Capture Permission -->
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
Class Class:
1. SurfaceView
View (View), which contains a special Surface for drawing. You can control the format and size of this Surface. Surfaceview controls the drawing position of this Surface.
2. SurfaceHolder
SurfaceHolder is an abstract interface to control surface. You can control the size and format of surface through SurfaceHolder, modify the pixels of surface, monitor the changes of surface, etc. SurfaceHolder is a typical interface of SurfaceView.
3. SurfaceHolder. Callback
Users can implement this interface to receive messages of surface changes. When used in 1 SurfaceView, it only works between SurfaceHolder. Callback. surfaceCreated () and SurfaceHolder. Callback. surfaceDestroyed (). The method for setting Callback is SurfaceHolder. addCallback.
Usage:
Step 1: Create a new Android project CameraTest, including two Activity: MainActivity and CameraActivity.
Step 2:
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:background="#FFFFFF"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout android:layout_height="wrap_content"
android:layout_width="match_parent">
<ImageView
android:id="@+id/main_image"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_width="match_parent"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:orientation="horizontal">
<Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/main_camera"
android:text=" Photographing "/>
<Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=" Quit "
android:id="@+id/main_quit"/>
</LinearLayout>
</RelativeLayout>
MainActivity.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Button cameraButton; // Photo button
private Button quitButton; // Exit button
private ImageView imageView; // Picture display
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
imageView = (ImageView) findViewById(R.id.main_image);
// Take pictures locally ( In sdcard Get files from )
Bitmap bitmap = getLoacalBitmap("/sdcard/mhc.jpg");
Log.e("msgTag", new File("/sdcard/mhc.jpg").exists()+"==========");
imageView .setImageBitmap(bitmap); // Settings Bitmap
cameraButton = (Button) findViewById(R.id.main_camera);
quitButton = (Button) findViewById(R.id.main_quit);
MainOnClickListener mainOnClickListener = new MainOnClickListener();
cameraButton.setOnClickListener(mainOnClickListener);
quitButton.setOnClickListener(mainOnClickListener);
}
private class MainOnClickListener implements OnClickListener{
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_camera:
startActivity(new Intent(MainActivity.this, CameraActivity.class));
break;
case R.id.main_quit:
MainActivity.this.finish();
break;
default:
break;
}
}
}
/**
* The required file is obtained according to the file path, and the file is encapsulated into Bitmap Object returns
* @param fileUrl
* @return
*/
public static Bitmap getLoacalBitmap(String fileUrl) {
try {
FileInputStream fis = new FileInputStream(fileUrl);
return BitmapFactory.decodeStream(fis); /// Turn circulation into Bitmap Picture
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
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:layout_height="match_parent"
android:background="#FFFFFF"
tools:context=".CameraActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SurfaceView
android:id="@+id/camera_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<Button
android:id="@+id/camera_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" Photographing " />
</LinearLayout>
</RelativeLayout>
CameraActivity.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class CameraActivity extends Activity {
private String tag ="CameraActivity";
private SurfaceView surfaceView;
//Surface Controller of
private SurfaceHolder surfaceHolder;
private Camera camera;
private Button saveButton;
// Callback interface for taking pictures
private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePictureTask().execute(data);
camera.startPreview();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
initViews();
}
private void initViews() {
saveButton = (Button) findViewById(R.id.camera_save);
surfaceView = (SurfaceView) findViewById(R.id.camera_preview);
surfaceHolder = surfaceView.getHolder();
// To SurfaceView Current holder SurfaceHolder 1 Callback objects.
// Users can receive this interface surface Message of change. When used in 1 A SurfaceView In mid-time,
// It's only in SurfaceHolder.Callback.surfaceCreated() And SurfaceHolder.Callback.surfaceDestroyed() Valid between.
// Settings Callback The method is SurfaceHolder.addCallback.
// Implementation process 1 General inheritance SurfaceView And implement SurfaceHolder.Callback Interface
surfaceHolder.addCallback(surfaceCallback);
// Settings surface You don't need your own maintenance cache
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
saveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
camera.takePicture(null, null, pictureCallback);
// Camera.takePicture(shutterCallback,rawCallback,pictureCallback );
// private ShutterCallback shutterCallback = new ShutterCallback(){
// public void onShutter(){
// /* Pressing the shutter will instantly execute the code here */
// }
// };
// private PictureCallback rawCallback = new PictureCallback(){
// public void onPictureTaken(byte[] _data, Camera _camera){
// /* If you need to handle it raw It's here Write code */
// }
// };
// // After taking pictures, Storage JPG File to sd Card
// PictureCallback pictureCallback=new PictureCallback(){
// public void onPictureTaken(byte[] data,Camera camera) {
// FileOutputStream outSteam=null;
// try{
// SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
// String times=format.format((new Date()));
// outSteam=new FileOutputStream("/sdcard/"+times+"mhc.jpg");
// outSteam.write(data);
// outSteam.close();
// }catch(FileNotFoundException e){
// Log.d("Camera", "row");
// } catch (IOException e) {
// e.printStackTrace();
// }
// };
// };
}
});
}
//SurfaceView Implementation of the callback interface of the current holder
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
Log.e(tag, " Camera Open Finish ");
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
camera.release();
camera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(ImageFormat.JPEG);
camera.setDisplayOrientation(0);
camera.setParameters(parameters);
camera.startPreview();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
};
class SavePictureTask extends AsyncTask<byte[], String, String> {
@Override
protected String doInBackground(byte[]... params) {
File picture = new File("/sdcard/mhc.jpg");
try {
FileOutputStream fos = new FileOutputStream(picture.getPath());
fos.write(params[0]);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e(tag, " Photo Save Complete ");
CameraActivity.this.finish();
return null;
}
}
}
Download address: Android realizes camera taking function