Get path and imagename of recently captured image through camera - android

I have to upload captured image to ftp server.I am capturing image through camera and i want to get image name and path of that image.I am using following code to get imagepath:
int ACTION_TAKE_PICTURE = 1;
String selectedImagePath;
Uri mCapturedImageURI;
Button loadButton;
ImageView img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_ftpsdemo);
img = (ImageView)findViewById(R.id.image);
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "yahoo.jpg");
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intentPicture,ACTION_TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == ACTION_TAKE_PICTURE){
selectedImagePath = getRealPathFromURI(mCapturedImageURI);
Log.v("selectedImagePath", selectedImagePath);
img.setImageBitmap( BitmapFactory.decodeFile(selectedImagePath));
}
}
public String getRealPathFromURI(Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
But i am getting imagepath like this:
/mnt/sdcard/DCIM/Camera/1352443194885.jpg
As i am saving name "yahoo.jpg".
I know this may be very simple question but i am unable to get imagename and path same.
So i am unable to upload image to ftp server.

check this...put this in your onActivityResult
Uri selectedImage = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Log.v("log","filePath is : "+filePath);

While creating a path you are just saving the "title". You are not giving the actual path and the filename that the camera should use to store. Because of this Camera is storing the file at its default location with the "Title" you have provided.
You are doing all fine in your code but just do the following to have the same filename:
Intead of :
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "yahoo.jpg");
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Use this:
StringBuilder path = new StringBuilder();
path.append(Environment.getExternalStorageDirectory());
path.append(// any location say "/Pictures/" //); // Do check if the folder is present. Else create one.
path.append("yahoo");
path.append(".jpg");
File file = new File(path.toString());
mCapturedImageURI = Uri.fromFile(file);

Use this to start the Intent for the Camera:
Oh. The Uri targetURI is a global declaration.
Intent getCameraImage = new Intent("android.media.action.IMAGE_CAPTURE");
File cameraFolder;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(),"your_app_name/camera");
else
cameraFolder= StatusUpdate.this.getCacheDir();
if(!cameraFolder.exists())
cameraFolder.mkdirs();
File photo = new File(Environment.getExternalStorageDirectory(), "your_app_name/camera/camera_snap.jpg");
getCameraImage.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
targetURI = Uri.fromFile(photo);
startActivityForResult(getCameraImage, 1);
And in the onActivityResult():
getContentResolver().notifyChange(targetURI, null);
ContentResolver cr = getContentResolver();
try {
// SET THE IMAGE FROM THE CAMERA TO THE IMAGEVIEW
bmpImageCamera = android.provider.MediaStore.Images.Media.getBitmap(cr, targetURI);
// SET THE IMAGE FROM THE GALLERY TO THE IMAGEVIEW
imgvwSelectedImage.setImageBitmap(bmpImageCamera);
} catch (Exception e) {
e.printStackTrace();
}
This piece of code creates a folder with a name of your choice. You can change the folder name here: new File(android.os.Environment.getExternalStorageDirectory(),"your_app_name/camera");
Also, this overwrites the camera_snap.jpg everytime you call the Intent to get a Camera image.
This code does not account for Out Of Memory exceptions, but is merely a demonstration of how to get Camera images back to your app.
EDIT: Almost forgot. If you haven't already done so, you will need to add this permission to your Manifest.xml: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I have a resolved the issue with the following code.It works for me.
I have referred this link:here
Just have to make filepath and imageName global variable
MyCameraActivity.java
public class MyCameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
public static String imageFilePath;
public static String imageName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File filePath = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
imageName = timeStamp +".jpg"; // name of captured image
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ imageName);
imageFilePath = mediaFile.toString(); // you can get path of image saved
return mediaFile;
}
}
CameraPreview.java:
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:id="#+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Capture" />
</LinearLayout>
Following permissions are required in androidmanifiest.xml:
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Now i can get imageName and imagepath of recently captured image and easily upload this image to ftp server.
Happy coding.

Related

how to capture picture portrait mode set portrait mode?

i have camera activity. and i capture picture but in camera preview not show picture portrait mode . how to possible in android . my code below .
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
protected static final int MEDIA_TYPE_IMAGE = 0;
static String FilePAth = "";
Button takePicture;
static String base64string="";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(CameraActivity.this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
takePicture = (Button) findViewById(R.id.btnTakePicture);
takePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
Log.v("log", " FilePAth " + FilePAth);
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Intent returnIntent = new Intent();
returnIntent.putExtra("data", data);
setResult(RESULT_OK, returnIntent);
finish();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("path", FilePAth);
setResult(RESULT_OK, returnIntent);
finish();
};
}
and get data :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("log", " data --> " + data.getByteArrayExtra("data"));
if (requestCode == 1) {
if (data.hasExtra("data")) {
Log.v("log", " request if ");
Bitmap b = BitmapFactory.decodeByteArray(
data.getByteArrayExtra("data"), 0,
data.getByteArrayExtra("data").length);
imgStorePicture.setImageBitmap(b);
/*imgStorePicture.setScaleType(ScaleType.FIT_XY);*/
base64string = Base64.encodeBytes(data
.getByteArrayExtra("data"));
Log.v("log", "base64string " + base64string);
}
}
}
The short answer is, you cannot. The picture is always returned the way it is. You can change preview orientation, but not the orientation of the JPEG image returned to your onPictureTaken).
But you can set JPEG rotation via Exif header without decoding it. This is the most efficient method, but some viewers may still show a rotated image.
Alternatively, you can use JPEG lossless rotation. The Android port is on GitHub.

Image capturing in android is working only on emulator not in phone

I have followed this
to take an image using android inbuilt camera and save the image in sd card. The code is working fine with the emulator. But when i installed the apk in phone(samsung galaxy s3). the application will not take images.
My code is follows. Please have a look.
public class MainActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
protected Context context = this;
public static int count = 0;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final String TAG = "MyCameraAppss";
private Camera autoCam ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
captureImage();
}
});
}
private void captureImage(){
//Detecting camera hardware
boolean isCameraAvailable = checkCameraHardware(context);
if(isCameraAvailable){
Toast.makeText(context, "Camera found", Toast.LENGTH_SHORT).show();
//Accessing cameras
autoCam = getCameraInstance();
if(autoCam!=null){
autoCam.open();
Toast.makeText(context, "Camera is accesses successfully", Toast.LENGTH_SHORT).show();
autoCam.takePicture(null, null, mPicture);
Toast.makeText(context, "picture is taken and going to sleep for a sec", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Toast.makeText(context, "Camera instance not available", Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "After slept going to release the camera", Toast.LENGTH_SHORT).show();
autoCam.release();
Toast.makeText(context, "Camera released successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "cannot access the camera", Toast.LENGTH_SHORT).show();
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Toast.makeText(context, "Error creating media file, check storage permissions:", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}else{
Toast.makeText(context, "Save: Pic file is found going to write", Toast.LENGTH_SHORT).show();
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(context, "Save: Pic is saved successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(context, "File not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Toast.makeText(context, "Error accessing file: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Error accessing file: " + e.getMessage());
}catch (Exception e) {
Toast.makeText(context, "Other Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp+"Amith" + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
The image is saved in the location
I have installed the apk on my phone and clicks the camera button mentioned in the first image, only "camera released toast" is displayed.
Is it necessary to load preview in our page?
i am very new with camera API.
Please guide me to resolve this
Thank you
This is my own blog here you will get description of your problem.
http://uniqueandroidtutorials.blogspot.in/2013/02/code-to-start-camera-with-build-in.html
Hope it will helps you..Thanks
Did you add this permission to AndroidManifest.xml file
<uses-feature android:name="android.hardware.camera" />
Then refer this codes. It work for me.
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
private static int RESULT_LOAD_IMAGE = 1;
public void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
if(latlon==null)
latlon="";
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "CERS");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath()+ File.separator+ timeStamp + "_--"+ latlon +"--.jpg");
}
return mediaFile;
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
IMGS.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
toast.ShowAlert("User cancelled image capture", 0,false);
} else {
// failed to capture image
toast.ShowAlert("Sorry! Failed to capture image",0,false);
}
}
/***/
/** Browse Images **/
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
IMGS.setImageBitmap(bitmap);
}
}

Not able to save Camera Images in Android

I am trying to save a image from camera. but its not working ..
Given permission
Code is pasted below. Not sure why its is not saving the image Code seems fine taken from developer.android site . Please help!
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private Display display;
private int PreviewSizeWidth = 640;
private int PreviewSizeHeight= 480;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera,getWindowManager().getDefaultDisplay());
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
Button captureButton = (Button) findViewById(R.id.button1);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
Log.d("Take","Picture");
mCamera.takePicture(null, null, mPicture);
// mCamera.stopPreview();
// mCamera.startPreview();
}
}
);
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("TAG","Callabaclk start");
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);;
if (pictureFile == null){
Log.d("TAG", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.d("Ok",pictureFile.getAbsolutePath());
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
//fos.write(data);
fos.flush();
fos.close();
Log.d("TAG","DONE");
} catch (FileNotFoundException e) {
Log.d("Test", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Test", "Error accessing file: " + e.getMessage());
}
}
};
public static Camera getCameraInstance(){
Camera c = null;
try {
Log.d("Test",Camera.getNumberOfCameras()+"");
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
Log.d("test", e.toString());
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public static boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
// File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES), "MyCameraApp");
File sampleDir = Environment.getExternalStorageDirectory();
File mediaStorageDir = new File(sampleDir.getPath()+File.separator+"Path");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
mediaStorageDir.mkdirs();
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
// mediaFile = new File(mediaStorageDir.getPath() + File.separator +"Path_"+ timeStamp + ".jpg");
mediaFile = new File(mediaStorageDir.getPath() ,"Path_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
When I do getPath() i get 08-14 02:31:52.153: D/Ok(4279): /storage/emulated/0/Path/Path_20130814_023152.jpg
After heck lot of research found it need to add these lines after fos.close :
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Path");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ mediaStorageDir)));
Thanks
Njoy
check permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
try to create a simple file
String path = Environment.getExternalStorageDirectory() + "/" + "test.jpg";
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Then verify whether you can save your picture

Retrieving pixel array from image taken with a camera

I am working on an app that needs to access an array of pixels from a picture after it is taken. The main Activity is below. I have a good amount of java experience but extremely limited experience with images past displaying them on the screen. I see the byte array being passed to the picture callback method but I do not know how it is formatted. How can I get a pixel array that includes the RGB components from the captured image? I tried to find this through the stack overflow forums however I got a few hundred pages of results and only searched through the first 10 or so, so I am sorry if that has already been asked and I just did not see it.
public class ConverterActivity extends Activity
{
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture = new PictureCallback() {
private String TAG;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
// Log.d(TAG, "Error creating media file, check storage permissions: " +
// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
// Create an instance of Camera
mCamera = Camera.open(this.getBackCamera());
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
#Override
protected void onPause()
{
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public int getBackCamera()
{
int numCameras = Camera.getNumberOfCameras();
CameraInfo cInfo = new CameraInfo();
for (int i = 0; i < numCameras; i++)
{
Camera.getCameraInfo(i, cInfo);
if (cInfo.facing == CameraInfo.CAMERA_FACING_BACK)
{
return i;
}
}
return -1;
}
}
If you take the picture using code like this:
imgFile = new File(Environment.getExternalStorageDirectory () + "/somefolder/" + name + ".jpg");
String fileName = imgFile.getAbsolutePath();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileName)));
startActivityForResult(intent, REQUEST_FROM_CAMERA);
Then you should be able to, when you get the result back from this intent, using code like this to access the bitmap
if (imgFile.exists()) {
String fileName = file.getAbsolutePath();
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm;
opts.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(fileName, opts);
return bm;
}
else return null;
Then you can use bitmapfactory tools, such as compress to stream and then
convert to byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); // 100 = max quality
byte[] byteArray = stream.toByteArray();

How to capture and save an image using custom camera in Android?

How do I capture an image in custom camera and then save that image in android?
please see below answer.
Custom_CameraActivity.java
public class Custom_CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:id="#+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Capture" />
</LinearLayout>
Add Below Lines to your androidmanifest.xml file
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
showbookimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/**
Here REQUEST_IMAGE is the unique integer value you can pass it any integer
**/
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
}
);
then u can now give the image a file name as follows and then convert it into bitmap and later on to file
private void createImageFile(Bitmap bitmap) throws IOException {
// Create an image file name
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
FileOutputStream stream = new FileOutputStream(image);
stream.write(bytes.toByteArray());
stream.close();
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
fileUri = image.getAbsolutePath();
Picasso.with(getActivity()).load(image).into(showbookimage);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){
// get bundle
Bundle extras = intent.getExtras();
// get
bitMap = (Bitmap) extras.get("data");
// showbookimage.setImageBitmap(bitMap);
try {
createImageFile(bitMap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
use picasso for images to display rather fast

Categories

Resources