Android to take pictures using com.google.android.cameraview.CameraView


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextPaint;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.cameraview.CameraView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


public class Ruzhu_Index_Activity extends AppCompatActivity implements Screensaver.OnTimeOutListener, View.OnClickListener {
private ImageButton imgbtn;
private ImageButton btnMenling;
private ImageButton dasao;
private ImageButton darao;
private LinearLayout text_menpai;
private TextView text_damenpai;
private ImageButton weixin;
private Screensaver mScreensaver;
private LinearLayout line_img_menling;
private LinearLayout line_text_menling;
the LinearLayout line_text_qingwudarao Private;
Private the LinearLayout linea_yingcangrenlian;
Private the LinearLayout linea_menpai;
int I;
// Play tone
Private Ringtone R & lt;

// video widget
Private static String the TAG = Final "the MainActivity";
Private Final static int = REQUEST_CAMERA_PERMISSION. 1;
Private CameraView mCameraView;
/ / child thread for processing image data
Private Handler mBackgroundHandler;
// rear camera
Private mCameraId int = Camera.CameraInfo.CAMERA_FACING_BACK;
// front camera
Private cameraId int = Camera.CameraInfo.CAMERA_FACING_FRONT;
Private static int to COMPLETED = Final 0;
// multi-thread calls
private Handler handler=new Handler(){
@SuppressLint("WrongConstant")
@Override
public void handleMessage(@NonNull Message msg) {
if (msg.what == COMPLETED) {
int num = btnMenling.getTextAlignment();
System.out.println(num);
if (num == 1) {
btnMenling.setBackground(getResources().getDrawable(R.drawable.btn1));
btnMenling.setTextAlignment(2);
} else {
btnMenling.setBackground(getResources().getDrawable(R.drawable.btn_doorbell_bell_unsel));
btnMenling.setTextAlignment(1);
}
}
}
};
@Override
protected void the onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.ruzhuindex);
// initialize control
the init ();
// button click event
btn ();
// Add a camera monitor callback
IF (mCameraView = null!) {
mCameraView.addCallback (mCallback);
}
// capture status screen
mScreensaver = new Screensaver (10000); // timer 5 seconds
mScreensaver.setOnTimeOutListener (this); // listening
mScreensaver. start (); // start the timer
// doorbell click
butn_menling ();
// bold font size
textsizi ();
// hide the title bar
IF (! getSupportActionBar () = null) {
getSupportActionBar () hide ();.
}
// transparent status bar
setStatusBarFullTransparent ();
}
// click event
Private void btn () {
/ / click event
imgbtn.setOnClickListener (the this);
darao.setOnClickListener (the this);
btnMenling.setOnClickListener (the this);
dasao.setOnClickListener (the this);
text_damenpai.setOnClickListener (the this);
}

// initialize control
private void init () {
// camera
mCameraView = findViewById (R.id.camera);
// other hidden menu functions
= the findViewById darao (R.id.darao);
line_text_qingwudarao = the findViewById (R.id.line_text_qingwudarao);
dasao = the findViewById (R.id.dasao);
Weixin = the findViewById (R.id.weixin);
// bell
line_img_menling = findViewById (R.id.line_img_menling);
btnMenling = the findViewById (R.id.btn_menlin);
line_text_menling = the findViewById (R.id.line_text_menling);
// menu
imgbtn = the findViewById (R.id.imgbut);
// house number
text_damenpai = the findViewById (R.id.text_damenpai);
linea_menpai = the findViewById (R.id.linea_menpai);
text_menpai = the findViewById (R.id.text_menpai);
text_menpai = the findViewById (R.id.text_menpai);
// face framing
linea_yingcangrenlian = findViewById (R.id.linea_yingcangrenlian);
}


// click event doorbell effect
Private void butn_menling () {
btnMenling.setOnClickListener (mOnClickListener);
}

// pictures click event
@SuppressLint ( "WrongConstant")
View.OnClickListener mOnClickListener new new View.OnClickListener = Private () {
@Override
public void the onClick (View View) {
Switch (view.getId ()) {
Case R.id.btn_menlin:
// play tone
defaule (getApplicationContext ());
// wake up the camera
if (! mCameraView.isCameraOpened ()) {
// start the front camera
mCameraView.setFacing (cameraId);
mCameraView.start ();
}
// wait a second photographing
new new Handler () postDelayed (the Runnable new new () {.
Public void RUN () {
// camera
if (mCameraView ! = null) {
mCameraView.takePicture ();
}
}
}, 1000);

text_damenpai.setVisibility (View.GONE);
text_menpai.setVisibility (View.VISIBLE);
linea_yingcangrenlian.setVisibility(View.VISIBLE);
linea_menpai.setVisibility(View.GONE);
btnMenling.setBackground(getResources().getDrawable(R.drawable.btn1));
final Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
int num = btnMenling.getTextAlignment();
Message msg = new Message();
msg.what = COMPLETED;
handler.sendMessage(msg);
if (i>2&&num==2){
i=0;
t.cancel();
}
i++;
}
},0,1000);
break;
}
}
};
//播放铃声
private void defaule(Context context){
if (r==null){
Log.e("----初始化铃声-----",getApplicationContext()+"");
String uri = "android.resource://" + context.getPackageName() + "/" + R.raw.dingdong;
Uri no = Uri.parse(uri);
RingtoneManager.getRingtone = R & lt (context.getApplicationContext (), NO);
}
(! r.isPlaying ()) {IF
Log.e ( "play ringtone -------- -----", getApplicationContext ( ) + "");
r.play ();

}
}

/ **
* dynamically acquiring and storing rights permissions camera
* /
@SuppressLint ( "WrongConstant")
protected void onResume () {
super.onResume ();
// check permissions If there is authority to start the camera, do not go to request permission
IF (ContextCompat.checkSelfPermission (the this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {

} the else {
ActivityCompat.requestPermissions (the this, new new String [] {Manifest. permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
// Get storage permission
IF (Build.VERSION.SDK_INT> = 23 is) {
IF (ContextCompat.checkSelfPermission (getApplicationContext (), Manifest.permission.WRITE_EXTERNAL_STORAGE) = PackageManager.PERMISSION_GRANTED) {!
ActivityCompat.requestPermissions (the this, String new new [] {} android.Manifest.permission.WRITE_EXTERNAL_STORAGE,. 1);
}
}
}
/ **
* Close the camera
* /
protected void the onPause () {
// turn off the camera, the camera release
mCameraView.stop ();
Log.e ( "** onPause () **" , " release the camera");
super.onPause ();
}
request permission // runtime
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (permissions.length != 1 || grantResults.length != 1) {
throw new RuntimeException("Error on requesting camera permission.");
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "grantResults[0]", Toast.LENGTH_SHORT).show();
}
break;
}
}
//在子线程保存图片
private Handler getBackgroundHandler(){
if (mBackgroundHandler==null){
HandlerThread thread=new HandlerThread("background");
thread.start();
mBackgroundHandler=new Handler(thread.getLooper());
}
return mBackgroundHandler;
}
//相机 监听回调事件
private CameraView.Callback mCallback = new CameraView.Callback() {
@Override
public void onCameraOpened(CameraView cameraView) {
Log.d(TAG, "打开相机");
}

@Override
public void onCameraClosed(CameraView cameraView) {
mCameraView.stop();
Log.d(TAG, "退出相机");
}

@Override
void onPictureTaken public (CameraView cameraView, Final byte [] Data) {
Log.d (the TAG, "*** onPictureTaken ***" data.length +);
Toast.makeText (cameraView.getContext (), "** * photographing * ", Toast.LENGTH_SHORT) .Show ();
. getBackgroundHandler () POST (new new Runnable () {
@Override
public void RUN () {
// save the picture in the child thread
the try {
Bitmap Bitmap = BitmapFactory.decodeByteArray (the Data, 0, data.length);
Log.d ( "length initialization *** ****", String.valueOf (data.length));

Log.i ( "WeChat", "size of the image before compression" + ( bitmap.getByteCount () / 1024/1024)
+ "M width" + bitmap.getWidth () + "height" + bitmap.getHeight ());
               in the phone DCIM // photo file / folder
                        FileName = String "/ sdcard / the DCIM /" + UUID.randomUUID () + ".jpg"; 
a FileOutputStream the outputStream new new = a FileOutputStream (fileName);
OutputStream.write (Data);
// determines whether the directory is available
File file = new File ( fileName); // create a file
IF (file.getParentFile (!) EXISTS ()) {.
file.getParentFile () mkdir ();. // create a folder
}
// path picture
String fa = file.getAbsolutePath () ;
// path generated according to the picture, re-compressed, and stored in memory
the compress (FA);
// delete files
deleteSingleFile (FA);
// Bitmap release
bitmap.recycle ();
Bitmap = null;
} the catch (Exception E) {
Toast.makeText ( "! camera failed" getApplicationContext (), + e.toString ( ), Toast.LENGTH_LONG) the .Show ();
Log.d ( "error message:", e.toString ());
e.printStackTrace ();
}
}
});
}
};

/ **
* image compression method, according to individual circumstances . This method needs to be compressed is called
* @param srcPath read the path
* /
public void the compress (by srcPath String) {
final String fileName = "/sdcard/DCIM/" + UUID.randomUUID() + ".jpg";
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
float hh = dm.heightPixels;
float ww = dm.widthPixels;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, opts);
opts.inJustDecodeBounds = false;
int w = opts.outWidth;
int h = opts.outHeight;
int size = 0;
if (w <= ww && h <= hh) {
size = 1;
} else {
? W = Double Scale> = H W / WW: H / HH;
Double The Math.log = log (Scale) / The Math.log (2);
Double logCeil Math.ceil = (log);
size = (int) the Math. POW (2, logCeil);
}
opts.inSampleSize = size;
Bitmap = BitmapFactory.decodeFile (by srcPath, the opts);
// rotate the image 90 °, the degree of rotation: 0-360, rotates according to the actual situation
Bitmap resizePicture = rotatePicture (Bitmap, 270);
ByteArrayOutputStream new new ByteArrayOutputStream BAOS = ();
int Quality = 100;
resizePicture.compress (Bitmap.CompressFormat.JPEG, Quality, BAOS);
System.out.println (baos.toByteArray () length.);
/ / if it is greater than 2M, the reduced circulation
while (baos.toByteArray().length > 45 * 1024) {
baos.reset();
resizePicture.compress(Bitmap.CompressFormat.JPEG, quality, baos);
quality -= 20;
System.out.println(baos.toByteArray().length);
Log.i("wechat", "压缩后图片的大小" + (resizePicture.getByteCount() / 1024 / 1024)
+ "M宽度为" + resizePicture.getWidth() + "高度为" + resizePicture.getHeight() +
" byte.lenght" + (baos.toByteArray().length) / 1024 + "KB " + "quality=" + quality);
}

try {
final File file = new File(fileName);//创建文件
if (!file.getParentFile().exists()) {
file.getParentFile () mkdir ();. // Create Folder
}
// write the bitmap stream
baos.writeTo (new new a FileOutputStream (fileName));
Final FA = file.getAbsolutePath String ();
Log.d ( " path ** ** pictures exist ", fa);
// when uploading base64 encoded bits, plus .replace (" + ","% 2B "), or to upload back to the emergence of failed
String encodeString = fileBase64String (fa) .replace ( "+", "%. 2B");
Toast.makeText ( "! in the documents" getApplicationContext (), "success camera, photos saved in the" + FA +, Toast.LENGTH_LONG) .Show ();
Log.d ( "** ** Base64", encodeString);
Final Where do you want String = "body =" + encodeString + "";
new Thread(new Runnable() {
@Override
RUN void public () {
String POST = HttpPost.SendPost (URL_LINK, Where do you want);
delete the photo after // uploaded successfully
deleteSingleFile (FA);
Log.d ( "** Data Sent **", post.toString () );
}
.}) Start ();
} the catch (Exception E) {
e.printStackTrace ();
} {the finally
the try {
baos.flush ();
baos.close ();
} the catch (IOException E) {
e.printStackTrace ();
}
}
}
/ ** delete a single file
* @param filePath $ name the file you want to delete the file name
* @Return a single file deleted successfully return true, otherwise false
* /
Private boolean deleteSingleFile (String filePath $ the Name) {
File File = new new File (filePath $ the Name);
// If the file path to the corresponding file exists and is a file, delete
IF (File.Exists () && file.isFile ()) {
IF (File.delete ()) {
Log.e ( "- Method--", "delete a single file" + filePath $ Name + "success!");
return to true;
} the else {
Log.e ( "- Method--", "delete a single file" + filePath $ Name + "failed!");
return false;
}
} the else {
the Log. e ( "- Method--", "delete a single file" + filePath $ Name + "does not exist!");
return false;
}
}
/ **
* rotating 90
* @param Bitmap
* @param Degree degree of rotation
* @return
* /
public Bitmap rotatePicture (Final Bitmap Bitmap, int Final Degree) {
the Matrix Matrix = new new the Matrix ();
matrix.postRotate (Degree);
resizeBitmap = Bitmap.createBitmap Bitmap (Bitmap, 0, 0, bitmap.getWidth (), bitmap.getHeight (), Matrix, to true);
return resizeBitmap;
}
/ **
* image transfer bse64
* @param path image path
* @ return
* /
Private fileBase64String String (String path) {
the try {
the FileInputStream new new FIS = the FileInputStream (path); // input stream is converted into
= New new ByteArrayOutputStream BAOS ByteArrayOutputStream ();
byte [] Buffer = new new byte [1024];
int COUNT = 0;
the while ((COUNT = fis.read (Buffer))> = 0) {
baos.write (Buffer, 0, COUNT ); // read the input stream and writes the output byte stream
}
fis.close (); // close file input stream
String uploadBuffer = new String (Base64.encodeToString ( baos.toByteArray (), Base64.NO_WRAP)) ; // Base64 encoding of
return uploadBuffer;
} the catch (Exception E) {
return null;
}

}
// bold font
Private void textsizi () {
the TextView TV = the findViewById (R.id.Btext);
TextPaint tp = tv.getPaint();
tp.setFakeBoldText(true);
}
//全透状态栏
protected void setStatusBarFullTransparent() {
if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
getWindow () addFlags (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);.
// virtual keyboard is also transparent
getWindow () addFlags (WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);.
}
}
@Override // time to perform this method will
public void onTimeOut (Screensaver Screensaver) {
// turn off the camera
mCameraView.stop ();
linea_yingcangrenlian.setVisibility (View.GONE);
linea_menpai.setVisibility (View.VISIBLE);
// initialize button label
imgbtn.setVisibility (View.VISIBLE);
// hide
darao. . setVisibility (View.GONE);
dasao.setVisibility (View.GONE);
weixin.setVisibility (View.GONE);
text_menpai.setVisibility(View.GONE);
text_damenpai.setVisibility(View.VISIBLE);
}

/**
* 单击事件
* @param view
*/
@SuppressLint("WrongConstant")
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.darao:
line_img_menling.setVisibility(View.GONE);
line_text_menling.setVisibility(View.GONE);
line_text_qingwudarao.setVisibility(View.VISIBLE);
int colr = darao.getTextAlignment();
if (1==colr){
darao.setBackground(getResources().getDrawable(R.drawable.btn_doorbell_dontdisturb_sel));
darao.setTextAlignment(2);
}
if (2==colr){
line_img_menling.setVisibility(View.VISIBLE);
line_text_menling.setVisibility(View.VISIBLE);
line_text_qingwudarao.setVisibility(View.GONE);
darao.setBackground(getResources().getDrawable(R.drawable.btn_doorbell_dontdisturb_unsel));
darao.setTextAlignment(1);
}
break;
case R.id.imgbut:
//菜单隐藏
imgbtn.setVisibility(View.GONE);
//请勿打扰显示-立即打扫显示-微信开门显示
darao.setVisibility(View.VISIBLE);
dasao.setVisibility(View.VISIBLE);
weixin.setVisibility(View.VISIBLE);
break;
case R.id.dasao:
Intent integer=new Intent(Ruzhu_Index_Activity.this, Dasao_Index_Activity.class);
startActivity(integer);
break;
case R.id.text_damenpai:
System.out.println(1111111);
Intent integer2=new Intent(Ruzhu_Index_Activity.this,Ganjing_Index_Activity.class);
startActivity(integer2);
break;
default:
break;
}
}

@Override
protected void onDestroy() {
super.onDestroy();
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
}

//定时调用
class task extends TimerTask {
@Override
public void run() {
The Message new new MSG = the Message ();
msg.what = to COMPLETED;
handler.sendMessage (MSG);
}
}
// This method will be executed when the touch
@Override
public Boolean dispatchTouchEvent (the MotionEvent EV) {
mScreensaver.resetTime (); // reset time
return super.dispatchTouchEvent (EV);
}
}


Finally do not forget the required permissions profile plus
<uses-permission android:name ="android.permission .MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
 

Guess you like

Origin www.cnblogs.com/liqipiao/p/11328679.html