Change the directory file - Android Camera - android

I have tried lots of camera examples for android, but this (http://androideity.com/2011/10/08/hello-camera/) is the firs I get to save images and view it on the gallery. But what I want to know is how to change the folder I save the images. I think actually it saves them on sdcard0/DCIM.
Here is the main activity:
public class Foto extends Activity implements SurfaceHolder.Callback{
private LayoutInflater myInflater = null;
Camera myCamera;
byte[] tempdata;
boolean myPreviewRunning = false;
private SurfaceHolder mySurfaceHolder;
private SurfaceView mySurfaceView;
ImageButton takePicture;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.foto);
mySurfaceView = (SurfaceView) findViewById(R.id.surface);
mySurfaceHolder = mySurfaceView.getHolder();
mySurfaceHolder.addCallback(this);
mySurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
myInflater = LayoutInflater.from(this);
View overView = myInflater.inflate(R.layout.segundacapa,null);
this.addContentView(overView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
takePicture = (ImageButton) findViewById(R.id.button);
takePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myCamera.takePicture(myShutterCallback, myPictureCallback, myJpeg);
}
});
}
ShutterCallback myShutterCallback = new ShutterCallback() {
#Override
public void onShutter() {
}
};
PictureCallback myPictureCallback = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera myCamera) {
// TODO Auto-generated method stub
}
};
PictureCallback myJpeg = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera myCamera) {
// TODO Auto-generated method stub
if(data != null){
tempdata = data;
done();
}
}
};
void done(){
Bitmap bm = BitmapFactory.decodeByteArray(tempdata, 0, tempdata.length);
String url = Images.Media.insertImage(getContentResolver(), bm, null, null);
bm.recycle();
Bundle bundle = new Bundle();
if(url != null){
bundle.putString("url",url);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
Toast.makeText(this, "Picture saved on" + url, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Picture can not be saved", Toast.LENGTH_SHORT).show();
}
finish();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
try{
if(myPreviewRunning){
myCamera.stopPreview();
myPreviewRunning = false;
}
Camera.Parameters p = myCamera.getParameters();
p.setPreviewSize(width,height);
myCamera.setParameters(p);
myCamera.setPreviewDisplay(holder);
myCamera.startPreview();
myPreviewRunning = true;
}catch(Exception e){}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
myCamera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
myCamera.stopPreview();
myPreviewRunning = false;
myCamera.release();
myCamera = null;
}
}
There is also an XML layout with a SurfaceView (called foto.xml) and another called segundacapa.xmlwith a button.
Thank you very much!!

Instead of using Images.Media to store the image on disk (which uses default location), you can use another flavour of insertImage(), which takes your file path. You should write the file before. You don't need to convert the onPictureTaken()->data to Bitmap; you simply write the byte[] to a Jpeg file.
FileOutputStream fos = openFileOutput("saved.jpg", Context.MODE_PRIVATE);
fos.write(data);
fos.close();
You can choose the file name as you wish; you can save the file with other parameters (see more about Context.openFileOutput(). You can open the wile on /sdcard if you wish, e.g.
FileOutputStream fos = new FileOutputStream("/sdcard/saved.jpg");
Note that you need to request permission to write to the SD Card; check that the following line appears in AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related

Android camera byte array

I am trying to get the camera working in Android. I successfully created an app which can show camera images in a SurfaceView.
Now I want to receive byte array from camera. Is it possible to receive byte array from camera?
public class AndroidCamera extends Activity implements SurfaceHolder.Callback {
TextView testView;
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
PictureCallback rawCallback;
ShutterCallback shutterCallback;
private final String tag = "VideoServer";
Button start, stop;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.startcamerapreview);
start.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
start_camera();
}
});
stop = (Button) findViewById(R.id.stopcamerapreview);
stop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
stop_camera();
}
});
surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("Log", "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
}
public void CheckByteArray() {
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
if (Arrays.equals(data, byteArray)) {
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "ERROR:" + e, 1)
.show();
}
}
});
}
private void start_camera() {
try {
camera = Camera.open();
} catch (RuntimeException e) {
Log.e(tag, "init_camera: " + e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
// modify parameter
param.setPreviewFrameRate(20);
param.setPreviewSize(176, 144);
camera.setParameters(param);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
CheckByteArray();
} catch (Exception e) {
Log.e(tag, "init_camera: " + e);
return;
}
}
private void stop_camera() {
camera.stopPreview();
camera.release();
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
I used this code to receive the byte array from image.
I want to compare camera's byte array to the images byte array. If cameras byte array contains my images byte array then simple 'hello message' needs to be shown.
To get byte array of taken photo you need to call method takePicture and pass third listener:
camera.takePicture(
null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//data is what you need
}
});
To compare byte arrays you can use java.util.Arrays.equals() method. But I think you will never get equal arrays...

How to change camera from front to back and back to front on button click in android

I am working on an android tablet application. I want to change camera from front to back and back to front on button. How can I achieve this ? I have tried several example but not getting proper response.
I am adding code also.
public class PhotoPreview extends Activity implements SurfaceHolder.Callback {
private Camera camera;
private ImageButton cameraClick;
private ImageButton cameraSwap;
SurfaceView surfaceView;
private SurfaceHolder mHolder;
boolean previewing = false;
String path = "";
LayoutInflater controlInflater = null;
Bitmap bmp;
Button cameraCancel;
private SharedPreferences myPrefs;
private int camId;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Photo preview Called $$$$$$$$$$$$$$$$$$ ");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.photo_preview);
myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
camId = myPrefs.getInt("camId",1);
System.out.println("CAM ID $$$$$$$$$$$$$$$$$$ "+camId);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
mHolder = surfaceView.getHolder();
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mHolder.addCallback(this);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
this.addContentView(viewControl, layoutParamsControl);
cameraClick = (ImageButton) findViewById(R.id.cameraClick);
cameraClick.setOnClickListener(cameraClickListener);
cameraCancel = (Button) findViewById(R.id.cameraCancel);
cameraCancel.setOnClickListener(cameraCancelClickListener);
cameraSwap = (ImageButton) findViewById(R.id.cameraSwap);
cameraSwap.setOnClickListener(swapCameraClickListener);
}
/*
* This is click event of Photo capture button
*/
private OnClickListener cameraClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
if (camera != null) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
}
};
/*
* This is click event of camera cancel button
*/
private OnClickListener cameraCancelClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
Intent intent = new Intent(PhotoPreview.this,
MainScreenActivity.class);
startActivity(intent);
}
};
/*
* This is click event of camera cancel button
*/
private OnClickListener swapCameraClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
if (camId == 0) {
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("camId", 1);
prefsEditor.commit();
} else {
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("camId", 0);
prefsEditor.commit();
}
System.out.println("CAM ID ^^^^^^^^^^^^^^^^^^^^ "+camId);
Intent intent = new Intent(PhotoPreview.this, PhotoPreview.class);
startActivity(intent);
}
};
// Handles when shutter open
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Easy_Measurement_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent(PhotoPreview.this,
VerticalAdjustmentActivity.class);
startActivity(intent);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// Set camera preview size,orientation,rotation using parameters
if (camera != null) {
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
camera.startPreview();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("CAM ID %%%%%%%%%%%%%%$$$$$$$$$$$$$$$$$$ "+camId);
camera = Camera.open(camId);
if (camera != null) {
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("Surface destroyed ***************");
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
}
you can open a camera using Camera.open(int i). you can use only one camera at a time. So release one and then open another. For example
public void onClick(View v) {
camera.stopPreview();
camera.release();
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);
setCameraDisplayOrientation(CameraActivity.this, currentCameraId, camera);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}

Android Save Image to SD Card

UPDATE
Added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to the manifest all works ok now.
Ok so I have a app I have started to create which in the end I want to be able to take a picture, which then takes you to another screen which lets you be able to "Use" or "Retake" the picture.
When the image is took it needs to be saved into a new folder on the SD Card, (if the folder is not there then it needs to create it). I had all this working a couple of weeks ago but after i did some editing and shut down eclipse I cant seem to get it back working?
The section for this is after int imageNum = 0; i have added imagesFolder.mkdirs(); which i belive is correct to create a new folder but even this seems not to be working now.
Now the image just gets took and neither the new folder gets created or the image gets saved.
public class AndroidCamera extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
}
});
}
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); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "BeatEmUp");
imagesFolder.mkdirs();
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
You should make sure the manifest lists the permission to write to the SD card:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android Intent to open new screen with picture

I have a app which at the moment takes a image using the camera, at the moment once the image is took it saves to a folder on the SD Card and then the same screen stays on so another picture can be took.
I am wanting it so when the image has been took and saved a new screen opens with the picture on the new screen.
I have made a new xml file punch.xml and java Punch.java and registerd them in the manifest I just cant figure out how to set the app to open a new screen with the picture that has just been took.
Im guessing it is something to do with opening a new Intent once the image has been saved.
Update
Ok so all working now execpt getting the image to show on the next screen?
Punch.java
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.punch);
String myRef = this.getIntent().getStringExtra("filepath");
}
AndroidCamera.java UPDATED TO REFLECT CODE CHANGES
public class AndroidCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
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); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
imagesFolder.mkdirs(); // <----
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getBaseContext(), Punch.class);
intent.putExtra("filepath",uriSavedImage);
//just using a request code of zero
int request=0;
startActivityForResult(intent,request);
}};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
UPDATE
Looking at the suggestion to use putExtra() how do I set and retrieve this value?
The problem here is that you are calling
camera.startPreview();
in your pictureTaken callback.
You replace it with your code from onClick and change it startActivityForResult():
Intent intent = new Intent(getBaseContext(), Punch.class);
intent.putExtra("filepath",uriSavedImage);
//just using a request code of zero
int request=0;
startActivityForResult(intent,request);
Then you can implement onActivityResult and call camera.StartPreview() from there.
Don't forget to setResult in your Punch activity
You could save a reference to the location of where the image is saved, put that in an intent to open a new activity. Start the new activity and show the image, allow the user to delete etc.
Intent intent = new Intent(getBaseContext(), target.class);
intent.putExtra("ImageReference", reference);
startActivity(intent);
Whereas target.class is the name of your activity class.
So in your code above you seem to be going about setting the intent fine. This will run immediately after taking a picture.
Obviously you will need to reference where you saved the file. Then in the new activity class you call Punch.class, you will need to do something like:-
String myRef = this.getIntent().getStringExtra("ImageReference");
This will mean that you passed the String file path from the main activity to the new Punch.class that you created. Here you can use the file path to open the image.

doing photos with the camera and save them in a specific folder

I'm working on an android application which allows the user to take some photos using the android camera.The user takes this pictures for competing to a photo contest.So, he takes a few photos, which should be saved into a specific destination and after a while he loops between those photos and decide with which one he will compete to the photo contest.
Well, for that the photos should be saved on a specific folder not in the gallery among other photos which are not for the contest.
Currently, I'm just saving the photos to SDcard and I don't know how should I do to save them in a certain folder.
I must say that I have already built my own camera but still don't know how to act when comes to saving the images.
And here is how it looks like:
public class EditPhoto extends Activity implements SurfaceHolder.Callback, OnClickListener {
static final int FOTO_MODE = 0;
private static final String TAG = "CameraTest";
Camera mCamera;
boolean mPreviewRunning = false;
private Context mContext = this;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//doing things
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback(){
public void onPictureTaken(byte[] imageData, Camera c) {
if (imageData != null) {
Intent mIntent = new Intent();
StoreByteImage(mContext, imageData, 50, "ImageName");
mCamera.startPreview();
Bundle b = new Bundle();
b.putByteArray("imageData", imageData);
Intent i = new Intent(mContext, ImageDisplayActivity.class);
i.putExtras(b);
startActivity(i);
setResult(FOTO_MODE, mIntent);
finish();
}
}
};
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onStop() {
Log.e(TAG, "onStop");
super.onStop();
}
public void surfaceCreated(SurfaceHolder holder) {
Log.e(TAG, "surfaceCreated");
mCamera = Camera.open();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.e(TAG, "surfaceChanged");
if (mPreviewRunning) {
mCamera.stopPreview();
}
Camera.Parameters p = mCamera.getParameters();
List<Size> sizes = p.getSupportedPictureSizes();
p.setPreviewSize(640, 480);
p.setPictureSize(213,350);
mCamera.setParameters(p);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning = true;
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(TAG, "surfaceDestroyed");
mCamera.stopPreview();
mPreviewRunning = false;
mCamera.release();
}
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
public void onClick(View arg0) {
mCamera.takePicture(null, mPictureCallback, mPictureCallback);
}
public static boolean StoreByteImage(Context mContext, byte[] imageData, int quality, String expName) {
File sdImageMainDirectory = new File("/sdcard");
FileOutputStream fileOutputStream = null;
String nameFile;
try {
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 5;
Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length,options);
fileOutputStream = new FileOutputStream(sdImageMainDirectory.toString() +"/image.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
myImage.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
If you could point me in the right direction I would apppreciate it.Thanks
Just add the folder name after sdcard (i.e. /sdcard/images/wildlife). To ensure that the specified folder exist, call the method File.mkdirs(). And please don't use the hard coded string /sdcard to access SDCard, use Environment.getExternalStorageDirectory method. Revert back for any query.
Edit:
public class ImageViewActivity extends Activity {
private String[] imageDirs;
private Spinner dirSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getDirs();
populateSpinner();
}
private void populateSpinner() {
dirSpinner = (Spinner) findViewById(R.id.dirSpinner);
ArrayAdapter<String> dirAdapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_spinner_dropdown_item, imageDirs);
dirAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dirSpinner.setAdapter(dirAdapter);
dirSpinner.setOnItemSelectedListener(new OnImageItemSelectedListener());
}
/**
* Retrieves all the image files in the given directory.
*/
public File[] retrieveContents(String dirPath) {
File parentDir = new File(dirPath);
if (!parentDir.exists()) {
return null;
}
if (!parentDir.isDirectory()) {
return null;
}
File[] fileContents = null;
FilenameFilter filter = new FilenameFilter();
fileContents = parentDir.listFiles(filter);
filter = null;
parentDir = null;
return fileContents;
}
/**
* Inner class to get images only.
*/
private class FilenameFilter implements FileFilter {
#Override
public boolean accept(File dir) {
return dir.getName().toLowerCase()
.endsWith(".jpg;*.bmp;*.png;*.gif");
}
}
/**
* Returns the names of sub-dirs in Images dir.
*/
private void getDirs() {
String parentDir = Environment.getExternalStorageDirectory()
+ "/Images";
File[] imageFolders = new File(parentDir).listFiles();
ArrayList<String> dirList = new ArrayList<String>();
for (int i = 0; i < imageFolders.length; i++) {
if (imageFolders[i].isDirectory()) {
dirList.add(imageFolders[i].getName());
}
}
imageDirs = (String[]) dirList.toArray(new String[0]);
}
public class OnImageItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
parent.getContext(),
"The dir is " + parent.getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
}

Categories

Resources