How to Capture Image from Custom Cameraview in Android

How to capture image from custom CameraView in Android?

try to use Surface View for creating dynamic camera view and set in your required portion.

following code try

variables set Class level (Global)

Button btn_capture;
Camera camera1;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
public static boolean previewing = false;

Following code in onCreate() method

getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = new SurfaceView(this);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
btn_capture = (Button) findViewById(R.id.button1);

surfaceView.setBackgroundResource(R.drawable.your_background_image);

if(!previewing){

camera1 = Camera.open();
if (camera1 != null){
try {
camera1.setDisplayOrientation(90);
camera1.setPreviewDisplay(surfaceHolder);
camera1.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

btn_capture.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

if(camera != null)
{
camera1.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);

}
}
});

Following code put after onCreate() in your class.

ShutterCallback myShutterCallback = new ShutterCallback(){

public void onShutter() {
// TODO Auto-generated method stub
}};

PictureCallback myPictureCallback_RAW = new PictureCallback(){

public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};

PictureCallback myPictureCallback_JPG = new PictureCallback(){

public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);

Bitmap correctBmp = Bitmap.createBitmap(bitmapPicture, 0, 0, bitmapPicture.getWidth(), bitmapPicture.getHeight(), null, true);

}};

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera1.stopPreview();
previewing = false;
}

if (camera1 != null){
try {
camera1.setPreviewDisplay(surfaceHolder);
camera1.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub

}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub

camera1.stopPreview();
camera1.release();
camera1 = null;
previewing = false;

}

in AndroidManifest.xml give user-permissions.

<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>

and also not forgot ( implements SurfaceHolder.Callback ) to the class.

Capture Image from Camera and Display in Activity

Here's an example activity that will launch the camera app and then retrieve the image and display it.

package edu.gvsu.cis.masl.camerademo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MyCameraActivity extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}

Note that the camera app itself gives you the ability to review/retake the image, and once an image is accepted, the activity displays it.

Here is the layout that the above activity uses. It is simply a LinearLayout containing a Button with id button1 and an ImageView with id imageview1:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>
<ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>

</LinearLayout>

And one final detail, be sure to add:

<uses-feature android:name="android.hardware.camera"></uses-feature> 

and if camera is optional to your app functionality. make sure to set require to false in the permission. like this

<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>

to your manifest.xml.

How to pass a captured image from custom camera to another activity?

openColourDetectorActivity(pictureFile);

public void openColourDetectorActivity(File file) {
Intent intent = new Intent(this, ColourDetectorActivity.class);
intent.putExtra("FILE", file.getPath());
startActivity(intent);
}

in ColourDetectorActivity :

new File(getIntent().getStringExtra("FILE"))

How to capture image by custom button from already opened front camera

I had a similar problem before.

Capturing the Camera image with placed 3d models.

i solved it with PixelCopy.

I'm adding my code of that part below.

I'm sorry that it's not going to be the straight-answer to your problem but i hope you get some ideas

ImageButton btn3 = (ImageButton)findViewById(R.id.camera_btn);
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takePhoto();
}
});

private String generateFilename() {

//현재시간을 기준으로 파일 이름 생성
String date =
new SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.getDefault()).format(new Date());
return Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES) + File.separator + "IM/" + date + "_screenshot.jpg";
}

private void saveBitmapToDisk(Bitmap bitmap, String filename) throws IOException {

//사용자의 갤러리에 IM 디렉토리 생성 및 Bitmap 을 JPEG 형식으로 갤러리에 저장
File out = new File(filename);
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
try (FileOutputStream outputStream = new FileOutputStream(filename);
ByteArrayOutputStream outputData = new ByteArrayOutputStream()) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputData);
outputData.writeTo(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
throw new IOException("Failed to save bitmap to disk", ex);
}
}

private void takePhoto(){
//PixelCopy 를 사용하여 카메라 화면과 object 를 bitmap 으로 생성
final String filename = generateFilename();
ArSceneView view = arFragment.getArSceneView();

final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(),
Bitmap.Config.ARGB_8888);

final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
PixelCopy.request(view, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap, filename);

//Media Scanning 실시
Uri uri = Uri.parse("file://" + filename);
Intent i = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
i.setData(uri);
sendBroadcast(i);

} catch (IOException e) {
Toast toast = Toast.makeText(AR_Activity.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
"스크린샷이 저장되었습니다.", Snackbar.LENGTH_LONG);
snackbar.setAction("갤러리에서 보기", v -> {
//어플 내에서 저장한 스크린샷을 확인 가능
File photoFile = new File(filename);

Uri photoURI = FileProvider.getUriForFile(AR_Activity.this,
AR_Activity.this.getPackageName() + ".ar.codelab.name.provider",
photoFile);
Intent intent = new Intent(Intent.ACTION_VIEW, photoURI);
intent.setDataAndType(photoURI, "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
});
snackbar.show();
} else {
Toast toast = Toast.makeText(AR_Activity.this,
"스크린샷 저장 실패!: " + copyResult, Toast.LENGTH_LONG);
toast.show();
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}
}

In custom camera is not getting clear image capture in android

Fixed the issue by adding below Code:-

Camera.Parameters params = c.getParameters();
if (params.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
c.setParameters(params);

Capture and display image with custom camera app

modify onActivityResult method like this

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {

String photoPath = (String) data.getExtras().get("result");
imageHolder.setImageBitmap(BitmapFactory.decodeFile("photoPath"));
}
}

Do some modification in your onPictureTaken method like this

 Intent returnIntent = getIntent();
returnIntent.putExtra("result", pictureFile.getAbsolutePath());
setResult(RESULT_OK, returnIntent);
finish();

Save the image from an ImageView(captured from camera) in my custom defined folder in the INTERNAL MEMORY

Got it working:

Code for saving:

    FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
refreshGallery(outFile);

Permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Finally:

Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!



Related Topics



Leave a reply



Submit