I need to create an app where when I click a photo it will save 3 jpegs is different focus modes(auto focus, Macro focus and Infinite focus) if possible and save it. I have made a basic camera app whoe code I am posting..Can you guys tell me how to implement this?
public class MainActivity extends Activity implements Constants,SurfaceHolder.Callback,Camera.PreviewCallback,
Camera.AutoFocusCallback, OnTouchListener{
private ViewFlipper myviewflipper;
private float initialXpoint;
private Camera mCamera;
private SurfaceView mPreviewSV;
private SurfaceHolder mSurfaceHolder;
private Button mCapture;
private Button mChange;
private Button mReturn;
private Button mLoad;
private ImageView mImageView;
private int mPicturesCaptured = 0;
boolean isCaptureClicked = false;
boolean encodingCompleted = false;
long startTime;
int currentFile = 0;
int initialPointer = -1;
int secondPointer = -1;
int direction = -1;
CameraSize picSize = BACK_CAM_PREVIEW_SIZE_3 ;
File mFile;
ArrayList<String> imagePath;
ProgressDialog mEncodingProgress;
DisplayTask mTask;
Bitmap mDisplayBitmap;
File path;
File[] files;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mFile = new File(Constants.Cameraeffect);
if (!mFile.exists())
mFile.mkdir();
setupUI();
}
private void setupUI()
{
mPreviewSV = (SurfaceView) findViewById(R.id.sv_cam_preview);
mCapture = (Button) findViewById(R.id.button_capture);
mChange = (Button) findViewById(R.id.toggle);
mReturn = (Button) findViewById(R.id.button_return);
mImageView = (ImageView) findViewById(R.id.display);
mImageView.setOnTouchListener(this);
mLoad = (Button) findViewById(R.id.button_load);
mSurfaceHolder = mPreviewSV.getHolder();
mSurfaceHolder.addCallback(this);
mCapture.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
deleteFiles();
mPicturesCaptured = 0;
isCaptureClicked = true;
startTime=System.currentTimeMillis();
progressUpdate();
}
});
mChange.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int res = getCurrentCameraId();
switch(res){
case 0:
stopCamera();
startCamera(Constants.FRONT_CAMERA);
break;
case 1:
stopCamera();
startCamera(Constants.BACK_CAMERA);
break;
}
}
});
mLoad.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
imagePath=ListAllFiles();
mImageView.bringToFront();
mImageView.setVisibility(View.VISIBLE);
mImageView.setImageBitmap(decodeFile(imagePath.get(0)));
mTask = new DisplayTask();
mTask.execute("");
}
});
mReturn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
private ArrayList<String> ListAllFiles() {
ArrayList<String> tFileList = new ArrayList<String>();
path= new File(Constants.Cameraeffect);
if( path.exists() ) {
files = path.listFiles();
for(int i=0; i<files.length; i++) {
tFileList.add(files[i].toString());
}
}
return tFileList;
}
public void deleteFiles() {
path= new File(Constants.Cameraeffect);
if( path.exists() ) {
files = path.listFiles();
for(int i=0; i<files.length; i++) {
files[i].delete();
}
}
}
#SuppressWarnings("unused")
int getCurrentCameraId() {
int mCameraId = -1;
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_BACK){
return Constants.BACK_CAMERA;
}
else if (ci.facing == CameraInfo.CAMERA_FACING_FRONT){
return Constants.FRONT_CAMERA;
}
}
return -1;
}
private void progressUpdate()
{
mEncodingProgress = new ProgressDialog(this);
mEncodingProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mEncodingProgress.setMessage("Encoding");
mEncodingProgress.setIndeterminate(false);
mEncodingProgress.show();
new Thread(new Runnable()
{
public void run()
{
while((System.currentTimeMillis()-startTime)<=5000)
{
try
{
Thread.sleep(10);
mEncodingProgress.setProgress(mPicturesCaptured + 1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}).start();
}
#SuppressWarnings("unused")
private void startCamera(int id)
{
try
{
if (mCamera != null)
stopCamera();
mCamera = Camera.open(id);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(1280,720);
parameters.setFocusMode("infinite");
parameters.setJpegQuality(100);
parameters.setAutoExposureLock(true);
parameters.setAutoWhiteBalanceLock(true);
parameters.setRotation(0);
mCamera.setDisplayOrientation(0);
mCamera.setParameters(parameters);
mCamera.setPreviewCallback(this);
mCamera.setPreviewDisplay(mPreviewSV.getHolder());
mCamera.startPreview();
}
catch (IOException e)
{
stopCamera();
}
}
private void stopCamera()
{
if (mCamera != null)
{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mPreviewSV.getHolder().removeCallback(this);
mCamera.release();
mCamera = null;
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
protected void onPause()
{
stopCamera();
super.onPause();
}
#Override
protected void onDestroy()
{
stopCamera();
super.onDestroy();
}
public void surfaceCreated(SurfaceHolder holder)
{
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
startCamera(0);
}
public void surfaceDestroyed(SurfaceHolder holder)
{
}
public void onPreviewFrame(byte[] data, Camera camera)
{
if (System.currentTimeMillis()-startTime<=5000)
{
savingJpegToSDCard(data);
}
else
{
if(mEncodingProgress!=null){
mEncodingProgress.dismiss();
mEncodingProgress=null;
encodingCompleted=true;
}
}
if(encodingCompleted){
/*
* Log.i("","sent to JNI");
*/
encodingCompleted=false;
}
}
public void onAutoFocus(boolean arg0, Camera arg1) {
// TODO Auto-generated method stub
}
public boolean onTouch(View arg0, MotionEvent event) {
Log.d("","srikrishna:: ontouch");
switch(event.getAction()){
case(MotionEvent.ACTION_DOWN):
initialPointer=(int) event.getX();
break;
case(MotionEvent.ACTION_MOVE):
secondPointer=(int) event.getX();
break;
case(MotionEvent.ACTION_UP):
initialPointer=(int) event.getX();
}
return true;
}
public Bitmap decodeFile(String fPath)
{
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
opts.inDither = false;
opts.inPurgeable = true;
opts.inInputShareable = true;
BitmapFactory.decodeFile(fPath, opts);
final int REQUIRED_SIZE = 500;
int scale = 1;
if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE)
{
final int heightRatio = Math
.round((float) opts.outHeight / (float) REQUIRED_SIZE);
final int widthRatio = Math
.round((float) opts.outWidth / (float) REQUIRED_SIZE);
scale = heightRatio < widthRatio ? heightRatio : widthRatio;//
}
opts.inJustDecodeBounds = false;
opts.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(fPath, opts).copy(
Bitmap.Config.RGB_565, false);
return bm;
}
private void savingJpegToSDCard(final byte[] b1)
{
try{
Camera.Parameters parameters = mCamera.getParameters();
Size size = parameters.getPreviewSize();
Log.i("","abh size width and height "+size.width + " "+size.height);
YuvImage image = new YuvImage(b1, parameters.getPreviewFormat(),size.width, size.height, null);
File file = new File(Constants.Cameraeffect + "/File" + mPicturesCaptured + ".jpeg");
FileOutputStream filecon = new FileOutputStream(file);
image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), 90,filecon);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
mPicturesCaptured++;
}
class DisplayTask extends AsyncTask<String, Bitmap, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
currentFile = 0;
}
#Override
protected Void doInBackground(String... params)
{
while(true){
Log.i("","abh imagePath.size() "+imagePath.size());
if(secondPointer-initialPointer >50)
{
Log.i("","abh currentFile "+currentFile);
mDisplayBitmap = decodeFile(imagePath.get(currentFile));
publishProgress(mDisplayBitmap);
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if(currentFile<=90)
currentFile++;
initialPointer=secondPointer;
}
}
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Bitmap... values)
{
super.onProgressUpdate(values);
mImageView.setImageBitmap(values[0]);
}
}
}
In your start camera method set the focus mode to the required one and start the camera. If you want to change it dynamically on click of button then you must call the start camera method with the required attributes. Make sure you are releasing camera[this is very imp] also note that the custom camera implementation in android is very buggy[many of the bugs are stil open just goggle it and see] i suggest you read it carefully and implement it.
Related
I'm having some problems with CameraSource when I want to take a picture using the camera.
All i want is take a picture with a button i made on the xml file and use 'CameraSource' to take the photo because i'm using 'TextRecognizer' too.
The Camera is working fine but the problem occurs when i press the button to take a picture.
Manifest File:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
My Variables:
SurfaceView cameraView;
TextView textView;
CameraSource camera_source;
final int RequestCameraPermissionID = 1001;
Class:
// Starting the CameraSource. This will be in the 'OnCreate' function. This function works.
private void OpenCameraSource(){
final TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.w("Steal_Activity", "Detector activity are not yet available");
Toast.makeText(getApplicationContext(),"Detector activity are not yet available",Toast.LENGTH_SHORT).show();
} else {
camera_source = new CameraSource.Builder(getApplicationContext(),textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Steal.this,
new String[]{android.Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
camera_source.start(cameraView.getHolder());
}catch (IOException ex){
ex.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera_source.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
// Some Stuff here
}
});
}
}
// This function will be launched when the button is pressed
public void OnClick_TakeShot(View view){
try{//I GET ERROR HERE
camera_source.takePicture(null,pictureCallback);
}catch (Exception ex){
Toast.makeText(getApplicationContext(),"Error:"+ex.toString(),Toast.LENGTH_LONG).show();
}
}
// Callback for 'takePicture'
CameraSource.PictureCallback pictureCallback = new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
File file_image = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"/pics");
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes , 0, bytes .length);
if(bitmap!=null){
if(!file_image.isDirectory()){
file_image.mkdir();
}
file_image=new File(file_image,"mylastpic.jpg");
try{
FileOutputStream fileOutputStream=new FileOutputStream(file_image);
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
catch(Exception exception) {
Toast.makeText(getApplicationContext(),"Error saving: "+ exception.toString(),Toast.LENGTH_LONG).show();
}
}
}
};
NOT WORKING WHEN I PRESS THE BUTTON TO TAKE PICTURE
Try using this way (i'm using OCR from Google Vision and for taking picture with CameraSource) Pd: the flash button i havent fix it yet...
YOU HAVE TO USE : compile 'com.google.android.gms:play-services-vision:9.2.1' in your dependecies for the OCR compatibility
public class CustomCamaraActivity extends BaseActivity implements Callback,
OnClickListener {
private Context context;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera camera;
private Button flipCamera;
private Button flashCameraButton;
private Button captureImage;
private Button BtnCapturarFoto;
private int cameraId;
private boolean flashmode = false;
private int rotation;
private ActionBar actionBar;
private CameraSource cameraSource;
private StringBuilder builder;
private TextView txTextoCapturado;
private static CustomCamaraActivity instance;
private Activity activity;
private String nombreProyecto;
public static final int REQUEST_IMAGE_CAPTURE = 0020;
private File file;
private String ubicacion;
private static final String TAG = "FOTOGRAFIA";
private int Height = 620, Width = 480;
private TextRecognizer recognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_camara_layout);
context = this;
// camera surface view created
cameraId = CameraInfo.CAMERA_FACING_BACK;
flipCamera = (Button) findViewById(R.id.flipCamera);
flashCameraButton = (Button) findViewById(R.id.flash);
captureImage = (Button) findViewById(R.id.captureImage);
BtnCapturarFoto = (Button) findViewById(R.id.btnCapturarFoto);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
txTextoCapturado = (TextView) findViewById(R.id.tvTextoCapturado);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
flipCamera.setOnClickListener(this);
captureImage.setOnClickListener(this);
flashCameraButton.setOnClickListener(this);
BtnCapturarFoto.setOnClickListener(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
/*if (Camera.getNumberOfCameras() > 1) {
flipCamera.setVisibility(View.VISIBLE);
}*/
if (!getBaseContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
flashCameraButton.setVisibility(View.GONE);
flipCamera.setVisibility(View.GONE);
}
recognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (recognizer.isOperational()) {
cameraSource = new CameraSource.Builder(getApplicationContext(), recognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setRequestedFps(15.0f)
.setAutoFocusEnabled(true)
.build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CustomCamaraActivity.this, new String[]{Manifest.permission.CAMERA}, 100);
return;
}
try {
releaseCamera();
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(cameraSource != null){
cameraSource.stop();
}
}
});
recognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items = detections.getDetectedItems();
if (items.size() != 0) {
builder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock it = items.valueAt(i);
builder.append(it.getValue());
}
final String read = builder.toString().trim();
//String read = builder.toString().trim().replace(" ", "").replace("\n", "");
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
txTextoCapturado.setText(read);
}
});
}catch (Exception ex){
Log.e("error","Error al actualizar texto OCR");
}
//It continues doing other things here
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
public String getUbicacion() {
return ubicacion;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
if (camera != null) {
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(camera != null){
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!openCamera(CameraInfo.CAMERA_FACING_BACK)) {
alertCameraDialog();
}
}
private boolean openCamera(int id) {
boolean result = false;
cameraId = id;
//releaseCamera();
try {
camera = Camera.open(cameraId);
} catch (Exception e) {
e.printStackTrace();
}
if (camera != null) {
try {
setUpCamera(camera);
camera.setErrorCallback(new ErrorCallback() {
#Override
public void onError(int error, Camera camera) {
}
});
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
result = true;
} catch (IOException e) {
e.printStackTrace();
result = false;
releaseCamera();
}
}
return result;
}
private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
rotation = getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
switch (rotation) {
case Surface.ROTATION_0:
degree = 0;
break;
case Surface.ROTATION_90:
degree = 90;
break;
case Surface.ROTATION_180:
degree = 180;
break;
case Surface.ROTATION_270:
degree = 270;
break;
default:
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// frontFacing
rotation = (info.orientation + degree) % 330;
rotation = (360 - rotation) % 360;
} else {
// Back-facing
rotation = (info.orientation - degree + 360) % 360;
}
c.setDisplayOrientation(rotation);
Parameters params = c.getParameters();
showFlashButton(params);
List<String> focusModes = params.getSupportedFlashModes();
if (focusModes != null) {
if (focusModes
.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
}
params.setRotation(rotation);
}
private void showFlashButton(Parameters params) {
boolean showFlash = (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH) && params.getFlashMode() != null)
&& params.getSupportedFlashModes() != null
&& params.getSupportedFocusModes().size() > 1;
flashCameraButton.setVisibility(showFlash ? View.VISIBLE
: View.INVISIBLE);
}
private void releaseCamera() {
try {
if (camera != null) {
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("error", e.toString());
camera = null;
}
}
private void releaseCameraSource() {
try {
if (cameraSource != null) {
cameraSource.stop();
cameraSource.release();
cameraSource = null;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("error", e.toString());
cameraSource = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.flash:
flashOnButton();
break;
case R.id.flipCamera:
flipCamera();
break;
case R.id.captureImage:
takeImage();
break;
case R.id.btnCapturarFoto:
takeImage();
break;
default:
break;
}
}
private void takeImage() {
try{
//openCamera(CameraInfo.CAMERA_FACING_BACK);
//releaseCameraSource();
//releaseCamera();
//openCamera(CameraInfo.CAMERA_FACING_BACK);
//setUpCamera(camera);
//Thread.sleep(1000);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
private File imageFile;
#Override
public void onPictureTaken(byte[] bytes) {
try {
// convert byte array into bitmap
Bitmap loadedImage = null;
Bitmap rotatedBitmap = null;
loadedImage = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
// rotate Image
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(rotation);
rotatedBitmap = Bitmap.createBitmap(loadedImage, 0, 0,
loadedImage.getWidth(), loadedImage.getHeight(),
rotateMatrix, false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(Environment
.getExternalStorageDirectory() + "/Demo");
} else {
folder = new File(Environment
.getExternalStorageDirectory() + "/Demo");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
java.util.Date date = new java.util.Date();
imageFile = new File(folder.getAbsolutePath()
+ File.separator
//+ new Timestamp(date.getTime()).toString()
+ "Image.jpg");
imageFile.createNewFile();
} else {
Toast.makeText(getBaseContext(), "Image Not saved",
Toast.LENGTH_SHORT).show();
return;
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
rotatedBitmap = resize(rotatedBitmap, 800, 600);
rotatedBitmap.compress(CompressFormat.JPEG, 100, ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN,
System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA,
imageFile.getAbsolutePath());
CustomCamaraActivity.this.getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
setResult(Activity.RESULT_OK); //add this
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}catch (Exception ex){
txTextoCapturado.setText("Error al capturar fotografia!");
}
}
private void flipCamera() {
int id = (cameraId == CameraInfo.CAMERA_FACING_BACK ? CameraInfo.CAMERA_FACING_FRONT
: CameraInfo.CAMERA_FACING_BACK);
if (!openCamera(id)) {
alertCameraDialog();
}
}
private void alertCameraDialog() {
AlertDialog.Builder dialog = createAlert(CustomCamaraActivity.this,
"Camera info", "error to open camera");
dialog.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
private Builder createAlert(Context context, String title, String message) {
AlertDialog.Builder dialog = new AlertDialog.Builder(
new ContextThemeWrapper(context,
android.R.style.Theme_Holo_Light_Dialog));
dialog.setIcon(R.drawable.ic_launcher);
if (title != null)
dialog.setTitle(title);
else
dialog.setTitle("Information");
dialog.setMessage(message);
dialog.setCancelable(false);
return dialog;
}
private void flashOnButton() {
if (camera != null) {
try {
Parameters param = camera.getParameters();
if (flashmode) {
param.setFlashMode(Parameters.FLASH_MODE_OFF);
flashCameraButton.setBackground(getResources().getDrawable(R.drawable.ic_flash_off));
} else {
param.setFlashMode(Parameters.FLASH_MODE_TORCH);
flashCameraButton.setBackground(getResources().getDrawable(R.drawable.ic_flash_on));
}
//param.setFlashMode(!flashmode ? Parameters.FLASH_MODE_TORCH : Parameters.FLASH_MODE_OFF);
camera.setParameters(param);
flashmode = !flashmode;
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
/**
* Metodo para cambiar el tamaƱo de la fotografia una resolucion predeterminada.
*
* #param image
* #param maxWidth
* #param maxHeight
* #return
*/
private Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioMax > 1) {
finalWidth = (int) ((float) maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float) maxWidth / ratioBitmap);
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
return image;
} else {
return image;
}
}
}
and here is the layout:
<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" >
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/tvTextoCapturado"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAlignment="center"
android:textColor="#color/white"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="10dp"
android:elevation="0dp"
android:orientation="horizontal"
android:weightSum="30">
<Button
android:id="#+id/flash"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/captureImage"
android:layout_alignBottom="#+id/captureImage"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_toLeftOf="#+id/captureImage"
android:layout_toStartOf="#+id/captureImage"
android:layout_weight="4"
android:background="#drawable/ic_flash_off"
android:gravity="center" />
<Button
android:id="#+id/captureImage"
android:layout_width="35dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_weight="10"
android:background="#android:drawable/ic_menu_camera"
android:visibility="gone" />
<Button
android:id="#+id/btnCapturarFoto"
style="#style/blue_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_weight="20"
android:elevation="0dp"
android:text="Tomar fotografia" />
<Button
android:id="#+id/flipCamera"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_toRightOf="#id/captureImage"
android:layout_weight="4"
android:background="#drawable/ic_rotate"
android:visibility="invisible" />
</LinearLayout>
You can achieve it by CameraSource class like this:
mCameraSource = builder
.setFlashMode(if (useFlash) Camera.Parameters.FLASH_MODE_TORCH else null)
.build()
Add below code to the button click listener:
mCameraSource.takePicture(null, CameraSource.PictureCallback { data ->
// here data is a byteArray, you can play with it :)
}
You have to add the XML object "SurfaceView" to your activity, not declare it as a variable :
In your main_activity.xml
<SurfaceView
android:id="#+id/cameraView"
android:layout_width="match_parent"
android:layout_height="300dp" />
In your activity.kt
val cameraView: SurfaceView = findViewById(R.id.cameraView)
I am working on Live Streaming application using RTMP. I am in the initial state, I successful done lot of things but now stuck on one place. I am using Surface view and my video is little bit stretched vertically. Codes are below:
This is my SrcCameraView
public class SrsCameraView extends GLSurfaceView implements GLSurfaceView.Renderer {
private GPUImageFilter magicFilter;
private SurfaceTexture surfaceTexture;
private int mOESTextureId = OpenGLUtils.NO_TEXTURE;
private int mSurfaceWidth;
private int mSurfaceHeight;
private int mPreviewWidth;
private int mPreviewHeight;
private boolean mIsEncoding;
private boolean mIsTorchOn = false;
private float mInputAspectRatio;
private float mOutputAspectRatio;
private float[] mProjectionMatrix = new float[16];
private float[] mSurfaceMatrix = new float[16];
private float[] mTransformMatrix = new float[16];
private Camera mCamera;
private ByteBuffer mGLPreviewBuffer;
private final static int PIXEL_FORMAT = ImageFormat.NV21;
private int mCamId = -1;
private int mPreviewRotation = 90;
private int mPreviewOrientation = Configuration.ORIENTATION_PORTRAIT;
private Thread worker;
private final Object writeLock = new Object();
private ConcurrentLinkedQueue<IntBuffer> mGLIntBufferCache = new
ConcurrentLinkedQueue<>();
private PreviewCallback mPrevCb;
public SrsCameraView(Context context) {
this(context, null);
}
public SrsCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
setEGLContextClientVersion(2);
setRenderer(this);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glDisable(GL10.GL_DITHER);
GLES20.glClearColor(0, 0, 0, 0);
magicFilter = new GPUImageFilter(MagicFilterType.NONE);
magicFilter.init(getContext().getApplicationContext());
magicFilter.onInputSizeChanged(mPreviewWidth, mPreviewHeight);
mOESTextureId = OpenGLUtils.getExternalOESTextureID();
surfaceTexture = new SurfaceTexture(mOESTextureId);
surfaceTexture.setOnFrameAvailableListener(new
SurfaceTexture.OnFrameAvailableListener() {
#Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
requestRender();
}
});
// For camera preview on activity creation
if (mCamera != null) {
try {
mCamera.setPreviewTexture(surfaceTexture);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
mSurfaceWidth = width;
mSurfaceHeight = height;
magicFilter.onDisplaySizeChanged(width, height);
mOutputAspectRatio = width > height ? (float) width / height : (float)
height / width;
float aspectRatio = mOutputAspectRatio / mInputAspectRatio;
if (width > height) {
Matrix.orthoM(mProjectionMatrix, 0, -1.0f, 1.0f, -aspectRatio,
aspectRatio, -1.0f, 1.0f);
} else {
Matrix.orthoM(mProjectionMatrix, 0, -aspectRatio, aspectRatio, -1.0f, 1.0f, -1.0f, 1.0f);
}
}
#Override
public void onDrawFrame(GL10 gl) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
surfaceTexture.updateTexImage();
surfaceTexture.getTransformMatrix(mSurfaceMatrix);
Matrix.multiplyMM(mTransformMatrix, 0, mSurfaceMatrix, 0,
mProjectionMatrix, 0);
magicFilter.setTextureTransformMatrix(mTransformMatrix);
magicFilter.onDrawFrame(mOESTextureId);
if (mIsEncoding) {
mGLIntBufferCache.add(magicFilter.getGLFboBuffer());
synchronized (writeLock) {
writeLock.notifyAll();
}
}
}
public void setPreviewCallback(PreviewCallback cb) {
mPrevCb = cb;
}
public int[] setPreviewResolution(int width, int height) {
getHolder().setFixedSize(width, height);
mCamera = openCamera();
mPreviewWidth = width;
mPreviewHeight = height;
Camera.Size rs = adaptPreviewResolution(mCamera.new Size(width,
height));
if (rs != null) {
mPreviewWidth = rs.width;
mPreviewHeight = rs.height;
}
mCamera.getParameters().setPreviewSize(mPreviewWidth, mPreviewHeight);
mGLPreviewBuffer = ByteBuffer.allocateDirect(mPreviewWidth *
mPreviewHeight * 4);
mInputAspectRatio = mPreviewWidth > mPreviewHeight ?
(float) mPreviewWidth / mPreviewHeight : (float) mPreviewHeight /
mPreviewWidth;
return new int[] { mPreviewWidth, mPreviewHeight };
}
public boolean setFilter(final MagicFilterType type) {
if (mCamera == null) {
return false;
}
queueEvent(new Runnable() {
#Override
public void run() {
if (magicFilter != null) {
magicFilter.destroy();
}
magicFilter = MagicFilterFactory.initFilters(type);
if (magicFilter != null) {
magicFilter.init(getContext().getApplicationContext());
magicFilter.onInputSizeChanged(mPreviewWidth,
mPreviewHeight);
magicFilter.onDisplaySizeChanged(mSurfaceWidth,
mSurfaceHeight);
}
}
});
requestRender();
return true;
}
private void deleteTextures() {
if (mOESTextureId != OpenGLUtils.NO_TEXTURE) {
queueEvent(new Runnable() {
#Override
public void run() {
GLES20.glDeleteTextures(1, new int[]{ mOESTextureId }, 0);
mOESTextureId = OpenGLUtils.NO_TEXTURE;
}
});
}
}
public void setCameraId(int id) {
mCamId = id;
setPreviewOrientation(mPreviewOrientation);
}
public void setPreviewOrientation(int orientation) {
mPreviewOrientation = orientation;
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(mCamId, info);
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
mPreviewRotation = info.orientation % 360;
mPreviewRotation = (360 - mPreviewRotation) % 360; // compensate the mirror
} else {
mPreviewRotation = (info.orientation + 360) % 360;
}
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
mPreviewRotation = (info.orientation + 90) % 360;
mPreviewRotation = (360 - mPreviewRotation) % 360; // compensate the mirror
} else {
mPreviewRotation = (info.orientation + 270) % 360;
}
}
}
public int getCameraId() {
return mCamId;
}
public void enableEncoding() {
worker = new Thread(new Runnable() {
#Override
public void run() {
while (!Thread.interrupted()) {
while (!mGLIntBufferCache.isEmpty()) {
IntBuffer picture = mGLIntBufferCache.poll();
mGLPreviewBuffer.asIntBuffer().put(picture.array());
mPrevCb.onGetRgbaFrame(mGLPreviewBuffer.array(),
mPreviewWidth, mPreviewHeight);
}
// Waiting for next frame
synchronized (writeLock) {
try {
// isEmpty() may take some time, so we set timeout to detect next frame
writeLock.wait(500);
} catch (InterruptedException ie) {
worker.interrupt();
}
}
}
}
});
worker.start();
mIsEncoding = true;
}
public void disableEncoding() {
mIsEncoding = false;
mGLIntBufferCache.clear();
if (worker != null) {
worker.interrupt();
try {
worker.join();
} catch (InterruptedException e) {
e.printStackTrace();
worker.interrupt();
}
worker = null;
}
}
public boolean startCamera() {
if (mCamera == null) {
mCamera = openCamera();
if (mCamera == null) {
return false;
}
}
Camera.Parameters params = mCamera.getParameters();
params.setPictureSize(mPreviewWidth, mPreviewHeight);
params.setPreviewSize(mPreviewWidth, mPreviewHeight);
int[] range = adaptFpsRange(SrsEncoder.VFPS,
params.getSupportedPreviewFpsRange());
params.setPreviewFpsRange(range[0], range[1]);
params.setPreviewFormat(ImageFormat.NV21);
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
params.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
List<String> supportedFocusModes = params.getSupportedFocusModes();
if (supportedFocusModes != null && !supportedFocusModes.isEmpty()) {
if
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else if
(supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.autoFocus(null);
} else {
params.setFocusMode(supportedFocusModes.get(0));
}
}
List<String> supportedFlashModes = params.getSupportedFlashModes();
if (supportedFlashModes != null && !supportedFlashModes.isEmpty()) {
if
(supportedFlashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
if (mIsTorchOn) {
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
}
} else {
params.setFlashMode(supportedFlashModes.get(0));
}
}
mCamera.setParameters(params);
mCamera.setDisplayOrientation(mPreviewRotation);
try {
mCamera.setPreviewTexture(surfaceTexture);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
return true;
}
public void stopCamera() {
disableEncoding();
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private Camera openCamera() {
Camera camera;
if (mCamId < 0) {
Camera.CameraInfo info = new Camera.CameraInfo();
int numCameras = Camera.getNumberOfCameras();
int frontCamId = -1;
int backCamId = -1;
for (int i = 0; i < numCameras; i++) {
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
backCamId = i;
} else if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{
frontCamId = i;
break;
}
}
if (frontCamId != -1) {
mCamId = frontCamId;
} else if (backCamId != -1) {
mCamId = backCamId;
} else {
mCamId = 0;
}
}
camera = Camera.open(mCamId);
return camera;
}
private Camera.Size adaptPreviewResolution(Camera.Size resolution) {
float diff = 100f;
float xdy = (float) resolution.width / (float) resolution.height;
Camera.Size best = null;
for (Camera.Size size :
mCamera.getParameters().getSupportedPreviewSizes()) {
if (size.equals(resolution)) {
return size;
}
float tmp = Math.abs(((float) size.width / (float) size.height) -
xdy);
if (tmp < diff) {
diff = tmp;
best = size;
}
}
return best;
}
private int[] adaptFpsRange(int expectedFps, List<int[]> fpsRanges) {
expectedFps *= 1000;
int[] closestRange = fpsRanges.get(0);
int measure = Math.abs(closestRange[0] - expectedFps) +
Math.abs(closestRange[1] - expectedFps);
for (int[] range : fpsRanges) {
if (range[0] <= expectedFps && range[1] >= expectedFps) {
int curMeasure = Math.abs(range[0] - expectedFps) +
Math.abs(range[1] - expectedFps);
if (curMeasure < measure) {
closestRange = range;
measure = curMeasure;
}
}
}
return closestRange;
}
public interface PreviewCallback {
void onGetRgbaFrame(byte[] data, int width, int height);
}
}
This is My Main Activity:
public class MainActivity extends AppCompatActivity implements RtmpHandler.RtmpListener,
SrsRecordHandler.SrsRecordListener, SrsEncodeHandler.SrsEncodeListener {
private static final String TAG = "Yasea";
Button btnPublish = null;
Button btnSwitchCamera = null;
Button btnRecord = null;
Button btnSwitchEncoder = null;
private SharedPreferences sp;
private String rtmpUrl = "rtmp://00.00.000.00/live/" + getRandomAlphaString(3) + '/' + getRandomAlphaDigitString(5);
private String recPath = Environment.getExternalStorageDirectory().getPath() + "/test.mp4";
private SrsPublisher mPublisher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
// response screen rotation event
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
// restore data.
sp = getSharedPreferences("Yasea", MODE_PRIVATE);
rtmpUrl = sp.getString("rtmpUrl", rtmpUrl);
// initialize url.
final EditText efu = (EditText) findViewById(R.id.url);
efu.setText(rtmpUrl);
btnPublish = (Button) findViewById(R.id.publish);
btnSwitchCamera = (Button) findViewById(R.id.swCam);
btnRecord = (Button) findViewById(R.id.record);
btnSwitchEncoder = (Button) findViewById(R.id.swEnc);
mPublisher = new SrsPublisher((SrsCameraView) findViewById(R.id.glsurfaceview_camera));
mPublisher.setEncodeHandler(new SrsEncodeHandler(this));
mPublisher.setRtmpHandler(new RtmpHandler(this));
mPublisher.setRecordHandler(new SrsRecordHandler(this));
mPublisher.setPreviewResolution(640, 480);
mPublisher.setOutputResolution(720, 1280);
mPublisher.setVideoHDMode();
mPublisher.startCamera();
btnPublish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnPublish.getText().toString().contentEquals("publish")) {
rtmpUrl = efu.getText().toString();
SharedPreferences.Editor editor = sp.edit();
editor.putString("rtmpUrl", rtmpUrl);
editor.apply();
mPublisher.startPublish(rtmpUrl);
mPublisher.startCamera();
if (btnSwitchEncoder.getText().toString().contentEquals("soft encoder")) {
Toast.makeText(getApplicationContext(), "Use hard encoder", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Use soft encoder", Toast.LENGTH_SHORT).show();
}
btnPublish.setText("stop");
btnSwitchEncoder.setEnabled(false);
} else if (btnPublish.getText().toString().contentEquals("stop")) {
mPublisher.stopPublish();
mPublisher.stopRecord();
btnPublish.setText("publish");
btnRecord.setText("record");
btnSwitchEncoder.setEnabled(true);
}
}
});
btnSwitchCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPublisher.switchCameraFace((mPublisher.getCamraId() + 1) % Camera.getNumberOfCameras());
}
});
btnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnRecord.getText().toString().contentEquals("record")) {
if (mPublisher.startRecord(recPath)) {
btnRecord.setText("pause");
}
} else if (btnRecord.getText().toString().contentEquals("pause")) {
mPublisher.pauseRecord();
btnRecord.setText("resume");
} else if (btnRecord.getText().toString().contentEquals("resume")) {
mPublisher.resumeRecord();
btnRecord.setText("pause");
}
}
});
btnSwitchEncoder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnSwitchEncoder.getText().toString().contentEquals("soft encoder")) {
mPublisher.switchToSoftEncoder();
btnSwitchEncoder.setText("hard encoder");
} else if (btnSwitchEncoder.getText().toString().contentEquals("hard encoder")) {
mPublisher.switchToHardEncoder();
btnSwitchEncoder.setText("soft encoder");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else {
switch (id) {
case R.id.cool_filter:
mPublisher.switchCameraFilter(MagicFilterType.COOL);
break;
case R.id.beauty_filter:
mPublisher.switchCameraFilter(MagicFilterType.BEAUTY);
break;
case R.id.early_bird_filter:
mPublisher.switchCameraFilter(MagicFilterType.EARLYBIRD);
break;
case R.id.evergreen_filter:
mPublisher.switchCameraFilter(MagicFilterType.EVERGREEN);
break;
case R.id.n1977_filter:
mPublisher.switchCameraFilter(MagicFilterType.N1977);
break;
case R.id.nostalgia_filter:
mPublisher.switchCameraFilter(MagicFilterType.NOSTALGIA);
break;
case R.id.romance_filter:
mPublisher.switchCameraFilter(MagicFilterType.ROMANCE);
break;
case R.id.sunrise_filter:
mPublisher.switchCameraFilter(MagicFilterType.SUNRISE);
break;
case R.id.sunset_filter:
mPublisher.switchCameraFilter(MagicFilterType.SUNSET);
break;
case R.id.tender_filter:
mPublisher.switchCameraFilter(MagicFilterType.TENDER);
break;
case R.id.toast_filter:
mPublisher.switchCameraFilter(MagicFilterType.TOASTER2);
break;
case R.id.valencia_filter:
mPublisher.switchCameraFilter(MagicFilterType.VALENCIA);
break;
case R.id.walden_filter:
mPublisher.switchCameraFilter(MagicFilterType.WALDEN);
break;
case R.id.warm_filter:
mPublisher.switchCameraFilter(MagicFilterType.WARM);
break;
case R.id.original_filter:
default:
mPublisher.switchCameraFilter(MagicFilterType.NONE);
break;
}
}
setTitle(item.getTitle());
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
final Button btn = (Button) findViewById(R.id.publish);
btn.setEnabled(true);
mPublisher.resumeRecord();
}
#Override
protected void onPause() {
super.onPause();
mPublisher.pauseRecord();
}
#Override
protected void onDestroy() {
super.onDestroy();
mPublisher.stopPublish();
mPublisher.stopRecord();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mPublisher.stopEncode();
mPublisher.stopRecord();
btnRecord.setText("record");
mPublisher.setScreenOrientation(newConfig.orientation);
if (btnPublish.getText().toString().contentEquals("stop")) {
mPublisher.startEncode();
}
mPublisher.startCamera();
}
private static String getRandomAlphaString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
private static String getRandomAlphaDigitString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
private void handleException(Exception e) {
try {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
mPublisher.stopPublish();
mPublisher.stopRecord();
btnPublish.setText("publish");
btnRecord.setText("record");
btnSwitchEncoder.setEnabled(true);
} catch (Exception e1) {
//
}
}
// Implementation of SrsRtmpListener.
#Override
public void onRtmpConnecting(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onRtmpConnected(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onRtmpVideoStreaming() {
}
#Override
public void onRtmpAudioStreaming() {
}
#Override
public void onRtmpStopped() {
Toast.makeText(getApplicationContext(), "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
public void onRtmpDisconnected() {
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onRtmpVideoFpsChanged(double fps) {
Log.i(TAG, String.format("Output Fps: %f", fps));
}
#Override
public void onRtmpVideoBitrateChanged(double bitrate) {
int rate = (int) bitrate;
if (rate / 1000 > 0) {
Log.i(TAG, String.format("Video bitrate: %f kbps", bitrate / 1000));
} else {
Log.i(TAG, String.format("Video bitrate: %d bps", rate));
}
}
#Override
public void onRtmpAudioBitrateChanged(double bitrate) {
int rate = (int) bitrate;
if (rate / 1000 > 0) {
Log.i(TAG, String.format("Audio bitrate: %f kbps", bitrate / 1000));
} else {
Log.i(TAG, String.format("Audio bitrate: %d bps", rate));
}
}
#Override
public void onRtmpSocketException(SocketException e) {
handleException(e);
}
#Override
public void onRtmpIOException(IOException e) {
handleException(e);
}
#Override
public void onRtmpIllegalArgumentException(IllegalArgumentException e) {
handleException(e);
}
#Override
public void onRtmpIllegalStateException(IllegalStateException e) {
handleException(e);
}
// Implementation of SrsRecordHandler.
#Override
public void onRecordPause() {
Toast.makeText(getApplicationContext(), "Record paused", Toast.LENGTH_SHORT).show();
}
#Override
public void onRecordResume() {
Toast.makeText(getApplicationContext(), "Record resumed", Toast.LENGTH_SHORT).show();
}
#Override
public void onRecordStarted(String msg) {
Toast.makeText(getApplicationContext(), "Recording file: " + msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onRecordFinished(String msg) {
Toast.makeText(getApplicationContext(), "MP4 file saved: " + msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onRecordIOException(IOException e) {
handleException(e);
}
#Override
public void onRecordIllegalArgumentException(IllegalArgumentException e) {
handleException(e);
}
// Implementation of SrsEncodeHandler.
#Override
public void onNetworkWeak() {
Toast.makeText(getApplicationContext(), "Network weak", Toast.LENGTH_SHORT).show();
}
#Override
public void onNetworkResume() {
Toast.makeText(getApplicationContext(), "Network resume", Toast.LENGTH_SHORT).show();
}
#Override
public void onEncodeIllegalArgumentException(IllegalArgumentException e) {
handleException(e);
}
}
I am not sure that this is the issue (a screenshot could have helped) but there might be a precision issue here (or even more in other places in the code):
mOutputAspectRatio = width > height ? (float) width / height : (float)
height / width;
Both width & height are integers. The result of their division is also an integer and hence it losses precision. I suggest you cast them both to float before the division:
mOutputAspectRatio = width > height ? ((float) width) / ((float)height) : ((float)
height) / ((float) width);
And the same for the computation of mInputAspectRatio.
public class CustomCameraActivity extends Activity implements
SurfaceHolder.Callback {
Camera camera = null;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
int flag = 0;
int which = 0;
Handler handler;
private boolean hasFlash;
private boolean isLighOn;
private Bitmap surfaceBitmap;
private Bitmap cameraBitmap;
private VerticalSeekBar greenSeekbar;
int vesion = 0;
public void turn() {
// myCamera is the Camera object
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
// only for android older than gingerbread
if (Camera.getNumberOfCameras() >= 2) {
vesion = 1;
camera.stopPreview();
camera.release();
// "which" is just an integer flag
switch (which) {
case 0:
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
which = 1;
break;
case 1:
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
which = 0;
break;
}
try {
camera.setPreviewDisplay(surfaceHolder);
// "this" is a SurfaceView which implements
// SurfaceHolder.Callback,
// as found in the code examples
camera.setPreviewCallback(null);
// camera.setPreviewCallback(this);
camera.startPreview();
} catch (IOException exception) {
camera.release();
camera = null;
}
vesion = 1;
} else {
AlertDialog.Builder ab = new AlertDialog.Builder(
CustomCameraActivity.this);
ab.setMessage("Device Having Only one Camera");
ab.setCancelable(false);
ab.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).show();
}
} else {
AlertDialog.Builder ab1 = new AlertDialog.Builder(
CustomCameraActivity.this);
ab1.setMessage("This Device Does Not Support Dual Camera Feature");
ab1.setCancelable(false);
ab1.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Constants.data1 = data;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(3);
this.surfaceView.setBackgroundColor(Color.argb(100, 0,
MotionEventCompat.ACTION_MASK, 0));
Button cap_btn = (Button) findViewById(R.id.button01);
Button retake = (Button) findViewById(R.id.retake);
Button use = (Button) findViewById(R.id.Use);
Button back = (Button) findViewById(R.id.back);
Button home = (Button) findViewById(R.id.home);
Button turn = (Button) findViewById(R.id.turn);
turn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
turn();
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flash();
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
use.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (flag >= 1) {
startActivity(new Intent(CustomCameraActivity.this,
Captured.class));
} else {
AlertDialog.Builder ab1 = new AlertDialog.Builder(
CustomCameraActivity.this);
ab1.setMessage("Please Capture Image");
ab1.setCancelable(false);
ab1.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).show();
}
flag = 0;
}
});
retake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.startPreview();
flag = 0;
}
});
cap_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(null, null, mPicture);
flag++;
}
});
}
public void flash() {
this.hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature("android.hardware.camera.flash");
if (this.hasFlash) {
Parameters p = camera.getParameters();
if (this.isLighOn) {
p.setFlashMode("off");
camera.setParameters(p);
camera.stopPreview();
camera.startPreview();
this.isLighOn = false;
return;
}
p.setFlashMode("torch");
camera.setParameters(p);
camera.stopPreview();
camera.startPreview();
this.isLighOn = true;
return;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
void setCameraDisplayOrientation(Activity activity, int cameraId,
Camera camera) {
if (camera != null) {
int result;
CameraInfo info = new CameraInfo();
int degrees = 0;
switch (activity.getWindowManager().getDefaultDisplay()
.getRotation()) {
case 0:
degrees = 0;
break;
case 1:
degrees = 90;
break;
case 2:
degrees = 180;
break;
case 3:
degrees = 270;
break;
}
if (info.facing == 1) {
result = (360 - ((info.orientation + degrees) % 360)) % 360;
} else {
result = ((info.orientation - degrees) + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (vesion == 1) {
Camera.open(which);
} else {
camera = Camera.open();
}
} catch (Exception e) {
camera.release();
}
try {
Parameters parameters = camera.getParameters();
if (getResources().getConfiguration().orientation != 2) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(this.surfaceHolder);
} catch (IOException e2) {
camera.release();
}
camera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
public void joinBitmap() {
this.surfaceView.setBackgroundColor(-16711936);
this.surfaceView.setDrawingCacheEnabled(true);
this.surfaceView.buildDrawingCache();
this.surfaceView.refreshDrawableState();
new Thread() {
public void run() {
try {
CustomCameraActivity.this.surfaceBitmap = CustomCameraActivity.this.surfaceView
.getDrawingCache();
if (CustomCameraActivity.this.surfaceBitmap != null) {
File pictureFile = CustomCameraActivity
.getOutputMediaFile();
if (pictureFile != null) {
Bitmap finalbitmap = CustomCameraActivity.overlay(
CustomCameraActivity.this.cameraBitmap,
CustomCameraActivity.this.surfaceBitmap,
CustomCameraActivity.this.greenSeekbar
.getProgress() + 15);
if (pictureFile.exists()) {
pictureFile.delete();
}
try {
FileOutputStream out = new FileOutputStream(
pictureFile);
finalbitmap.compress(CompressFormat.JPEG, 90,
out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
} catch (IOException e2) {
}
CustomCameraActivity.this.handler
.sendEmptyMessage(1);
return;
}
return;
}
CustomCameraActivity.this.handler.sendEmptyMessage(0);
} catch (Exception e3) {
}
}
}.start();
}
#SuppressLint({ "SimpleDateFormat" })
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"Night Vision Camera");
if (mediaStorageDir.exists() || mediaStorageDir.mkdirs()) {
return new File(
mediaStorageDir.getPath()
+ File.separator
+ "IMG_"
+ new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date()) + ".jpg");
}
return null;
}
public static Bitmap overlay(Bitmap bitmap1, Bitmap bitmapOverlay,
int opacity) {
Bitmap resultBitmap = Bitmap.createBitmap(bitmapOverlay.getWidth(),
bitmapOverlay.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(resultBitmap);
c.drawBitmap(bitmap1, 0.0f, 0.0f, null);
Paint p = new Paint();
p.setAlpha(opacity);
c.drawBitmap(bitmapOverlay, 0.0f, 0.0f, p);
return resultBitmap;
}
}
Here, I`m creating an image overlay on surface view and when i click on image to capture it, how to save it with that image that is overlayed on it? Please help and thanks in Advance. The image is captured but it is not saved with that image that is overlayed on the surface view.
You can use surfaceview.getDrawingCache();
this will return a Bitmap from your SurfaceView and then you can use it or save it in storage.
surfaceview.getDrawingCache(); does not work on surface, because surface is separate view than others view you have to get bitmpa on picturetaken method.
jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
camera.startPreview();
Bitmap cameraBitmap = BitmapFactory.decodeByteArray
(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.postRotate(90);
pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setTitle("Wait!");
pd.setMessage("capturing image.........");
pd.setIndeterminate(false);
pd.show();
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
// Update the progress status
progressStatus += 1;
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
// Update the progress status
pd.setProgress(progressStatus);
// If task execution completed
if (progressStatus == 100) {
// Dismiss/hide the progress dialog
pd.dismiss();
}
}
});
}
}
}).start();
Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
if (rotatedBitmap != null) {
rotatedBitmap = combinebitmap(rotatedBitmap, bitmapMap);
Random num = new Random();
int nu = num.nextInt(1000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
String picId = String.valueOf(nu);
String myfile = "Ghost" + picId + ".jpeg";
File dir_image = new File(Environment.getExternalStorageDirectory() +//<---
File.separator + "LiveCamera"); //<---
dir_image.mkdirs(); //<---
try {
File tmpFile = new File(dir_image, myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Toast.makeText(getApplicationContext(),
" Image saved at :LiveCamera", Toast.LENGTH_LONG).show();
camera.startPreview();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(MainActivity.this,
new String[]{dir_image.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
safeToTakePicture = true;
}
}
};
Hi aim working n android application to detect page number using camera preview.
After i received frame from OnPreviewFrame i'm doing real time image processing using opencv to find page number position .Now my question is How can i draw rectangle on surface View ?
Use this code
PreviewDemo.java
public class PreviewDemo extends Activity implements OnClickListener {
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
ImageView image;
Bitmap bmp, itembmp;
static Bitmap mutableBitmap;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
File imageFileName = null;
File imageFileFolder = null;
private MediaScannerConnection msConn;
Display d;
int screenhgt, screenwdh;
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview);
image = (ImageView) findViewById(R.id.image);
preview = (SurfaceView) findViewById(R.id.surface);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
previewHolder.setFixedSize(getWindow().getWindowManager()
.getDefaultDisplay().getWidth(), getWindow().getWindowManager()
.getDefaultDisplay().getHeight());
}
#Override
public void onResume() {
super.onResume();
camera = Camera.open();
}
#Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera = null;
inPreview = false;
super.onPause();
}
private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size: parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return (result);
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(PreviewDemo.this, t.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height,
parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
camera.setParameters(parameters);
camera.startPreview();
inPreview = true;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(final byte[] data, final Camera camera) {
dialog = ProgressDialog.show(PreviewDemo.this, "", "Saving Photo");
new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (Exception ex) {}
onPictureTake(data, camera);
}
}.start();
}
};
public void onPictureTake(byte[] data, Camera camera) {
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
savePhoto(mutableBitmap);
dialog.dismiss();
}
class SavePhotoTask extends AsyncTask < byte[], String, String > {#Override
protected String doInBackground(byte[]...jpeg) {
File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return (null);
}
}
public void savePhoto(Bitmap bmp) {
imageFileFolder = new File(Environment.getExternalStorageDirectory(), "Rotate");
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH)) + fromInt(c.get(Calendar.DAY_OF_MONTH)) + fromInt(c.get(Calendar.YEAR)) + fromInt(c.get(Calendar.HOUR_OF_DAY)) + fromInt(c.get(Calendar.MINUTE)) + fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
scanPhoto(imageFileName.toString());
out = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public String fromInt(int val) {
return String.valueOf(val);
}
public void scanPhoto(final String imageFileName) {
msConn = new MediaScannerConnection(PreviewDemo.this, new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msConn.scanFile(imageFileName, null);
Log.i("msClient obj in Photo Utility", "connection established");
}
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
Log.i("msClient obj in Photo Utility", "scan completed");
}
});
msConn.connect();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
onBack();
}
return super.onKeyDown(keyCode, event);
}
public void onBack() {
Log.e("onBack :", "yes");
camera.takePicture(null, null, photoCallback);
inPreview = false;
}
#Override
public void onClick(View v) {
}
}
Preview.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.view.SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Add the Permissions also
I am working with custom camera and recording video using custom camera.I am using fragment with viewpager.I am getting one issue when i am recording video,the value of camera is not null,but when i switch my activity, "the screen goes black and the value of camera is null".I am stuffing this problem from 15 days.,and not getting any proper solution.I have seen many answers and links on stack overflow but that is not giving me satisfactory solution. I have done following things below,here is my code.
public class Recording_Activity extends Fragment implements View.OnTouchListener {
private AlertDialog dialog;
private Context mContext;
private AlertDialog.Builder builder;
private Context context;
private LinearLayout layout;
private FrameLayout myCameraPreview ;
//private ToggleButton btn_toggle;
private ImageView btn_record_image,iv_unlock,iv_cross,iv_progress,btn_toggle;
private Button btn_music,btn_invitefriends,myButton,btn_clock_count;
private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
private SurfaceHolder surfaceHolder;
private boolean recording=false;
private RelativeLayout harmony_layout,backlayout,record_layout;
private int check_value;
private SurfaceHolder mHolder;
private int temp = 1;
private int i=0;
private int _xDelta,_yDelta;
private TextView tv_harmony,tv_unlock;
private File mFileTemp = null;
private String workingPath;
private SharedPreferences sharedPreferences;
private Editor editor;
TranslateAnimation animation ;
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private final long startTime = 10 * 1000;
private final long interval = 1 * 1000;
private int which;
private int currentCameraId;
private boolean inPreview;
CameraInfo camInfo = new CameraInfo();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.recording_screen, null);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
editor = sharedPreferences.edit();
countDownTimer = new MyCountDownTimer(startTime, interval);
btn_toggle=(ImageView)root.findViewById(R.id.btn_toggle);
btn_invitefriends=(Button)root.findViewById(R.id.btn_invitefriends);
btn_music=(Button)root.findViewById(R.id.btn_music);
layout=(LinearLayout)root.findViewById(R.id.layout);
myCameraPreview = (FrameLayout)root.findViewById(R.id.videoview);
tv_unlock = (TextView)root.findViewById(R.id.tv_unlock);
//timer = (TextView)root. findViewById(R.id.timer);
iv_unlock = (ImageView)root.findViewById(R.id.iv_unlock);
harmony_layout = (RelativeLayout)root.findViewById(R.id.harmony_layout);
btn_record_image = (ImageView)root.findViewById(R.id.btn_record_image);
btn_clock_count = (Button)root.findViewById(R.id.btn_clock_count);
tv_harmony = (TextView)root.findViewById(R.id.tv_harmony);
iv_cross = (ImageView)root.findViewById(R.id.iv_cross);
iv_progress= (ImageView)root.findViewById(R.id.iv_progress);
record_layout = (RelativeLayout)root.findViewById(R.id.recording_layout);
tv_harmony.getBackground().setAlpha(50);
btn_toggle.getBackground().setAlpha(80);
btn_clock_count.setAlpha(50);
iv_cross.setAlpha(80);
btn_record_image.setOnTouchListener(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT ,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = getResources().getDimensionPixelSize(R.dimen.record_btn_margin_left);
layoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.record_btn_margin_top);
btn_record_image.setLayoutParams(layoutParams);
mContext=getActivity();
builder=new AlertDialog.Builder(getActivity());
check_value = sharedPreferences.getInt(PreferenceConstants.VIDEO_CHANCE_REMAINING,3) ;
tv_unlock.setText(String.valueOf(check_value));
if (check_value <=0) {
iv_unlock.setVisibility(View.VISIBLE);
tv_unlock.setVisibility(View.INVISIBLE);
}
iv_unlock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater =getActivity().getLayoutInflater();
View myview = inflater.inflate(R.layout.clock_layout, null);
builder.setView(myview);
dialog=builder.create();
dialog = builder.show();
ImageView image = (ImageView)myview.findViewById(R.id.cross);
ListView list = (ListView)myview.findViewById(R.id.listView1);
list.setAdapter(new PurchaseListAdapter(getActivity()));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
}
});
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
});
iv_cross.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),Home.class);
startActivity(intent);
}
});
btn_clock_count.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater =getActivity().getLayoutInflater();
View myview = inflater.inflate(R.layout.clock_layout, null);
builder.setView(myview);
dialog=builder.create();
dialog = builder.show();
ImageView image = (ImageView)myview.findViewById(R.id.cross);
ListView list = (ListView)myview.findViewById(R.id.listView1);
list.setAdapter(new PurchaseListAdapter(getActivity()));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {}
});
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
});
btn_music.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Boolean isLoggedin = sharedPreferences.getBoolean(PreferenceConstants.IS_LOGGED_IN, false);
if(isLoggedin){
PreferenceConstants.obj.setUpView(0);
}
else{
AlertDialog dialog = Utils.alertDialogWithMessage(getActivity(),getString(R.string.guest_user_cannot_logged_in));
dialog.show();
}
}
});
btn_invitefriends.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Boolean isLoggedin = sharedPreferences.getBoolean(PreferenceConstants.IS_LOGGED_IN, false);
if(isLoggedin){
PreferenceConstants.obj.setUpView(2);
}
else{
AlertDialog dialog = Utils.alertDialogWithMessage(getActivity(),getString(R.string.guest_user_cannot_logged_in));
dialog.show();
}
}
});
btn_toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
flipcamera();;
Log.i("clk", "sucess");
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
this.context = getActivity();
workingPath = Environment.getExternalStorageDirectory() + "/Scatta";
myCamera = getCameraInstance();
if(this.myCamera == null){
Toast.makeText(getActivity(),
"Fail to get Camera",
Toast.LENGTH_LONG).show();
}
myCameraSurfaceView = new MyCameraSurfaceView(getActivity(), myCamera);
myCameraPreview.addView(myCameraSurfaceView);
return root;
}
private void flipcamera()
{
if (inPreview ) {
myCamera.stopPreview();
}
//NB: if you don't release the current camera before switching, you app will crash
myCamera.release();
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
myCamera = Camera.open(currentCameraId);
myCamera.setDisplayOrientation(90);
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
myCamera = Camera.open();
myCamera.setDisplayOrientation(90);
}
/* myCamera = Camera.open(currentCameraId);
myCamera.setDisplayOrientation(90);*/
try {
//this step is critical or preview on new camera will no know where to render to
myCamera.setPreviewDisplay(mHolder);
} catch (IOException e) {
e.printStackTrace();
}
myCamera.startPreview();
}
private Camera getCameraInstance(){
// Camera c = null;
Log.d("No of cameras",Camera.getNumberOfCameras()+"");
for (currentCameraId = 0; currentCameraId < Camera.getNumberOfCameras(); currentCameraId++) {
Camera.getCameraInfo(currentCameraId, camInfo);
if (camInfo.facing==(Camera.CameraInfo.CAMERA_FACING_FRONT )) {
myCamera = Camera.open(currentCameraId);
myCamera.setDisplayOrientation(90);
// CameraInfo cameraInfo = new CameraInfo();
// int rotation = (cameraInfo.orientation - 180 + 360) % 360;
Log.d("No of cameras",Camera.CameraInfo.CAMERA_FACING_FRONT+"");
}
}
if (camInfo.facing==(Camera.CameraInfo.CAMERA_FACING_BACK)) {
try {
myCamera.release();
myCamera = Camera.open();
myCamera.setDisplayOrientation(90);
Log.d("No of cameras",Camera.CameraInfo.CAMERA_FACING_BACK+"");
} catch (Exception e) {
e.printStackTrace();
System.err.println("ecepytion"+e.toString());
}
}
return myCamera;
}
private boolean prepareMediaRecorder(){
myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();
myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
createDir(Environment.getExternalStorageDirectory().toString(), "Scatta");
mediaRecorder.setOutputFile("/sdcard/Scatta/Scatta" + "temp" + ".mp4");
mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
mediaRecorder.setMaxDuration(60000);
mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
mediaRecorder.setOrientationHint(270);
try {
mediaRecorder.setPreviewDisplay(mHolder.getSurface());
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
private void createDir(String path, String dirName){
String newFolder = "/" + dirName;
File myNewFolder = new File(path + newFolder);
myNewFolder.mkdir();
mFileTemp = new File(workingPath,newFolder);
}
#Override
public void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera();
myCameraPreview.removeView(myCameraSurfaceView);// release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
myCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (myCamera != null){
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}
public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
//private SurfaceHolder mHolder;
//private Camera mCamera;
#SuppressWarnings("deprecation")
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
myCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int weight,
int height) {
if (mHolder.getSurface() == null){
return;
}
try {
myCamera.setPreviewDisplay(mHolder);
myCamera.startPreview();
// mCamera.unlock();
} catch (Exception e){
e.printStackTrace();
System.out.println("surface changed error"+e);
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
myCamera.setPreviewDisplay(holder);
myCamera.startPreview();
// mCamera.unlock();
} catch (IOException e){
e.printStackTrace();
System.out.println("IOException"+e);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
/*mCamera.release();*/
}
}
public static Fragment newInstance(Context _context) {
Recording_Activity f = new Recording_Activity();
return f;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
_xDelta = X- lParams.leftMargin;
_yDelta = Y- lParams.topMargin;
System.out.println("_xaDelta value"+_xDelta);
System.out.println("_yDelta value"+_yDelta);
if (camInfo.facing==(Camera.CameraInfo.CAMERA_FACING_BACK)) {
try {
myCamera.release();
myCamera = Camera.open();
myCamera.setDisplayOrientation(90);
Log.d("No of cameras",Camera.CameraInfo.CAMERA_FACING_BACK+"");
mediaRecorder.start();
recording =true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("ecepytion"+e.toString());
}
}
/*if(!recording){
releaseCamera();
if(!prepareMediaRecorder()){
Toast.makeText(getActivity(),
"Wait camera is preparing",
Toast.LENGTH_LONG).show();
startActivity(new Intent(getActivity(),FragmentClass.class));
}
else{
try {
mediaRecorder.start();
recording = true;
btn_record_image.setBackgroundResource(R.drawable.btn_pressed_icon);
PreferenceConstants._mViewPager.setPagingEnabled(false);
onAnimate(v);
countDownTimer.start();
iv_progress.setDrawingCacheEnabled(true);
btn_clock_count.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("camera error"+e.toString());
}
}*/
if (!recording) {
releaseCamera();
if (!prepareMediaRecorder()) {
Toast.makeText(getActivity(),
"Wait camera is preparing", Toast.LENGTH_LONG)
.show();
startActivity(new Intent(getActivity(),
FragmentClass.class));
} else {
try {
Log.v("Media Recorder", "Start");
Log.v("Camera Info", camInfo.facing + "");
/*if (camInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
mediaRecorder.start();
recording = true;
}*/
mediaRecorder.start();
recording = true;
btn_record_image
.setBackgroundResource(R.drawable.btn_pressed_icon);
PreferenceConstants._mViewPager.setPagingEnabled(false);
onAnimate(v);
countDownTimer.start();
iv_progress.setDrawingCacheEnabled(true);
btn_clock_count.setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
} catch (Exception e) {
e.printStackTrace();
System.out.println("camera error" + e.toString());
}
}
}
break;
case MotionEvent.ACTION_UP:
File mFile = new File("The output file's absolutePath");
if(recording){
try{
mediaRecorder.stop();
PreferenceConstants._mViewPager.setPagingEnabled(true);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
btn_record_image.setLayoutParams(layoutParams);
Intent i = new Intent(getActivity(),PlaybackScreen.class);
startActivity(i);
iv_progress.setDrawingCacheEnabled(false);
}
catch(RuntimeException e) {
mFile.delete(); //you must delete the outputfile when the recorder stop failed.
} finally {
releaseMediaRecorder();
mediaRecorder = null;
}
btn_record_image.setBackgroundResource(R.drawable.btn_unpressed_icon);
recording = false;
temp++;
countDownTimer.cancel();
animation.cancel();
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
if(check_value > 0)
{
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
v.setLayoutParams(layoutParams);
btn_clock_count.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
}
break;
}
layout.invalidate();
return true;
}
#Override
public void onResume() {
super.onResume();
Boolean isLoggedin = sharedPreferences.getBoolean(PreferenceConstants.IS_LOGGED_IN, false);
if(isLoggedin){
PreferenceConstants._mViewPager.setPagingEnabled(true);
}
else{
PreferenceConstants._mViewPager.setPagingEnabled(false);
iv_cross.setVisibility(View.VISIBLE);
}
}
public void onAnimate(View v) {
animation = new TranslateAnimation(0.0f, 400.0f,
0.0f, 0.0f);
animation.setDuration(8000); // animation duration
iv_progress.startAnimation(animation);
animation.setFillAfter(false);
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onTick(long millisUntilFinished) {
btn_clock_count.setText("" + millisUntilFinished / 1000);
btn_clock_count.setGravity(Gravity.CENTER );
}
#Override
public void onFinish() {
Intent i = new Intent(getActivity(),PlaybackScreen.class);
startActivity(i);
}
}
}