How to Capture and Save an Image Using Custom Camera in Android

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!

Can't save captured image in folder using custom camera in android

Your code is doing the correct thing, so save the image file to the device, but it is saving it to the result of the path returned here:

mFile = getActivity().getExternalFilesDir(null); 

The external file dir is probably pointing to myapp/data/data which is the 'sandbox' data area reserved for files that your app writes to external storage. This is not the same as the Downloads folder, which is saving files down to the shared (re: outside of sandbox) data area on the phone.

If you wanted to save to Downloads, you would probably have to write your images to an external website, then pass the https:// path to a ViewIntent which would display your image in a browser session, and give you the option to download the image from there.

In your code, you have:

mFile = getActivity().getExternalFilesDir(null);

But I don't see where mFile is declared in Image Reader. In your other class, you define it as a File. if mFile is a File, then you should probably be doing something like:

String mPath = getActivity().getExternalFilesDir(null);
File mFile = new File(mPath + "/temp.jpg");

// but I don't think you need to create a file, just use the path
ImageSaver saver = new ImageSaver(mCapturedImage,mPath);

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 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.

Take a photo using custom camera in android

What I need for is a bitmap of the taken image in order to use it in another Activity. Thanks in advance!

All you need is decode byte array received from camera, and then rotate it for right orientation.

Get camera display orientation:

private static int getCameraDisplayOrientation(int cameraId, Activity activity) {
int rotation = ((WindowManager)activity.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getRotation();
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + rotation) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - rotation + 360) % 360;
}
return result;
}

Decode byte array to bitmap:

public static Bitmap decodeByteArray(byte[] data, float rotationDegree) {
try {
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
if (rotationDegree != 0) {
bm = createRotatedBitmap(bm, rotationDegree);
}
return bm;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}

Rotate bitmap:

public static Bitmap createRotatedBitmap(Bitmap bm, float rotation) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation, bm.getWidth()/2, bm.getHeight()/2);
try {
Bitmap result = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
return result;
} catch (OutOfMemoryError e) {
return null;
}
}

Capture image with camera in android and save with a custom name

File outFile = new File(Environment.getExternalStorageDirectory(), "myname.jpeg");
FileOutputStream fos = new FileOutputStream(outFile);
photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();

you would also need to add Permission in Android Manifest.

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

the snippet will save the content of photo inside /sdcard with the name "myname.jpeg"

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 an image and store it with the native Android Camera

Have you checked what the output of Environment.getExternalStorageDirectory() is, because if it does not contain a trailing file seperator (/) then your image will end up in a directory that does not reside on the SDcard such as:

 /mnt/sdcardmake_machine_example.jpg

When what you really want is:

 /mnt/sdcard/make_machine_example.jpg

Try this code instead:

 _path = Environment.getExternalStorageDirectory() + File.separator +  "make_machine_example.jpg";


Related Topics



Leave a reply



Submit