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) {
}
}
}
Related
I am developing an app for custom camera and custom gallery. My image capturing is done very well but not set to grid view. What mistake did I do in my code? How can I set capture image to my grid view and how that image path will pass to next?
//Main Activity
public class MainActivity extends AppCompatActivity {
Camera camera;
ImageView imageView ;
FrameLayout frameLayout;
showCamera showCamera;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout=(FrameLayout)findViewById(R.id.frame);
imageView = (ImageView)findViewById(R.id.imageView);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA},
50); }
// Create an instance of Camera
camera = getCameraInstance();
showCamera=new showCamera(this,camera);
frameLayout.addView(showCamera);
Button captureButton = (Button) findViewById(R.id.captureFront);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
CaptureImage(v);
File file = getOutputMediaFile();
Log.e("use_pic buttn ", file.getPath());
Intent intent = new Intent();
intent.putExtra("output", file.getPath());
}
}
);
Button gallarybutton = (Button) findViewById(R.id.gallary);
gallarybutton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,CustomGallary.class);
startActivity(i);
}
}
);
}
Camera.PictureCallback mpictureCallback=new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File picture_file = getOutputMediaFile();
if(picture_file== null)
{
return;
}
else
{
try {
FileOutputStream fos=new FileOutputStream(picture_file);
fos.write(data);
camera.startPreview();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
private File getOutputMediaFile() {
String state= Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED))
{
return null;
}
else
{
File folder_gui= new File(Environment.getExternalStorageDirectory()+ File.separator + "GUI");
if(!folder_gui.exists())
{
folder_gui.mkdir();
}
File outputFile= new File(folder_gui,"temp.jpg");
return outputFile;
}
}
public void CaptureImage(View v)
{
if(camera!=null)
{
camera.takePicture(null,null,mpictureCallback);
}
}
/** 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)
}
return c; // returns null if camera is unavailable
}
}
In this code I have an error: My grid view is not set image capture by custom camera
//CustomGallary.java
public class CustomGallary extends AppCompatActivity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_view);
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("output");
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
bitmapArray.add(bitmap); // Add a bitmap
//bitmapArray.get(0); // Get first bitmap
GridView mygrid=findViewById(R.id.gv);
ImageView iv=findViewById(R.id.imageView);
Log.e("Helloo", String.valueOf(bitmap));
ArrayAdapter<Bitmap> adapter = new ArrayAdapter<Bitmap>(this,R.layout.gv_item, bitmapArray);
mygrid.setAdapter(adapter);
}
}
I am implementing android-gpuimage library in my code.
https://github.com/CyberAgent/android-gpuimage
I used the camera code of the sample project. Everyting works fine, but whenever I switch the camera, front camera opens in the side in a small view. I want the front camera to occupy the whole Surfaceview.
Here is my code:
public class CameraActivity extends Activity implements OnSeekBarChangeListener, OnClickListener {
private GPUImage mGPUImage;
private CameraHelper mCameraHelper;
private CameraLoader mCamera;
private GPUImageFilter mFilter;
private int cameraId;
private FilterAdjuster mFilterAdjuster;
static int camerastate=0;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
((SeekBar) findViewById(R.id.seekBar)).setOnSeekBarChangeListener(this);
findViewById(R.id.filter).setOnClickListener(this);
findViewById(R.id.flipCamera).setOnClickListener(this);
findViewById(R.id.captureImage).setOnClickListener(this);
cameraId = CameraInfo.CAMERA_FACING_BACK;
mGPUImage = new GPUImage(this);
mGPUImage.setImage(mImage);
mGPUImage.setFilter(mGPUImageFilter);
mGPUImage.getBitmapWithFilterApplied();*/
mGPUImage.setGLSurfaceView((GLSurfaceView) findViewById(R.id.surfaceView));
mCameraHelper = new CameraHelper(this);
mCamera = new CameraLoader();
}
#Override
protected void onResume() {
super.onResume();
mCamera.onResume();
}
#Override
protected void onPause() {
mCamera.onPause();
super.onPause();
}
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.filter:
GPUImageFilterTools.showDialog(this, new OnGpuImageFilterChosenListener() {
#Override
public void onGpuImageFilterChosenListener(final GPUImageFilter filter) {
switchFilterTo(filter);
}
});
break;
case R.id.captureImage:
if (mCamera.mCameraInstance.getParameters().getFocusMode().equals(
Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
takePicture();
} else {
mCamera.mCameraInstance.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(final boolean success, final Camera camera) {
takePicture();
}
});
}
break;
case R.id.flipCamera:
mCamera.switchCamera();
break;
}
}
private void takePicture() {
// TODO get a size that is about the size of the screen
Camera.Parameters params = mCamera.mCameraInstance.getParameters();
params.setRotation(90);
mCamera.mCameraInstance.setParameters(params);
for (Camera.Size size : params.getSupportedPictureSizes()) {
Log.i("ASDF", "Supported: " + size.width + "x" + size.height);
}
mCamera.mCameraInstance.takePicture(null, null,
new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, final Camera camera) {
final File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d("ASDF",
"Error creating media file, check storage permissions");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("ASDF", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("ASDF", "Error accessing file: " + e.getMessage());
}
data = null;
Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
mGPUImage1.setImage(pictureFile);
mGPUImage1.setFilter(new GPUImageSepiaFilter());
final GLSurfaceView view = (GLSurfaceView) findViewById(R.id.surfaceView);
view.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
mGPUImage1.saveToPictures(bitmap1, "GPUImage",
System.currentTimeMillis() + ".jpg",
new OnPictureSavedListener() {
#Override
public void onPictureSaved(final Uri
uri) {
pictureFile.delete();
camera.startPreview();
view.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
});
Log.e("Activity", "GPUIMAGE " + mGPUImage.toString());
}
});
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static File getOutputMediaFile(final 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;
}
private void switchFilterTo(final GPUImageFilter filter) {
if (mFilter == null
|| (filter != null && !mFilter.getClass().equals(filter.getClass()))) {
mFilter = filter;
mGPUImage.setFilter(mFilter);
mFilterAdjuster = new FilterAdjuster(mFilter);
}
}
#Override
public void onProgressChanged(final SeekBar seekBar, final int progress,
final boolean fromUser) {
if (mFilterAdjuster != null) {
mFilterAdjuster.adjust(progress);
}
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(final SeekBar seekBar) {
}
private class CameraLoader {
int mCurrentCameraId = 0;
Camera mCameraInstance;
public void onResume() {
setUpCamera(mCurrentCameraId);
}
public void onPause() {
releaseCamera();
}
public void switchCamera() {
releaseCamera();
mCurrentCameraId = (mCurrentCameraId + 1) % mCameraHelper.getNumberOfCameras();
setUpCamera(mCurrentCameraId);
}
private void setUpCamera(int id) {
Log.e("Activity", "ID1 " + id);
mCameraInstance = getCameraInstance(id);
Camera.Parameters parameters = mCameraInstance.getParameters();
// TODO adjust by getting supportedPreviewSizes and then choosing
// the best one for screen size (best fill screen)
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
parameters.setPictureSize(640,480);
mCameraInstance.setParameters(parameters);
int orientation = mCameraHelper.getCameraDisplayOrientation(
CameraActivity.this, mCurrentCameraId);
CameraInfo2 cameraInfo = new CameraInfo2();
mCameraHelper.getCameraInfo(mCurrentCameraId, cameraInfo);
boolean flipHorizontal = cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT;
mGPUImage.setUpCamera(mCameraInstance, orientation, flipHorizontal, false);
}
/** A safe way to get an instance of the Camera object. */
private Camera getCameraInstance(int id) {
Camera c = null;
Log.e("Activity","Camera Instance " + id);
try {
c = mCameraHelper.openCamera(id);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
private void releaseCamera() {
mCameraInstance.setPreviewCallback(null);
mCameraInstance.stopPreview();
mCameraInstance.release();
mCameraInstance= null;
}
}
}
EDIT:
SCreenshot of my camera: when i press the switch camera button, the back view stops and my front view starts in the corner.
i tested it in other device. The switchcamera feature is working perfectly.but, it is not working correctly in some devices.
This will surely fix your issue :
**How to switch**
public void switchCamera() {
releaseCamera();
mCameraId = (mCameraId + 1) % Camera.getNumberOfCameras();
**mGpuImageView.reInitLayout();**//the trick
prepareCamera();
}
**releaseCamera**
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
**prepareCamera**
your camera prepare method
**mGpuImageView.reInitLayout**
//Put this inside your GPUImageView.java class
public void reInitLayout() {
mGLSurfaceView.requestLayout();
mGPUImage.deleteImage();
}
Let me know if you face any further issue.
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Set this for fill_parent and check.
Could you check this and paste screen
<ImageView
android:id="#+id/img_switch_camera"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
android:layout_weight="0.08"
android:src="#drawable/ic_switch_camera" />
It supose to change size for 300x300
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" />
I am developing a custom camera application and testing on two galaxy tablets.. one 7inch and one 10inch.. the 10 inch works great but on the 7inch, when i take a picture, it freezes the camera preview and the logCat stops at CAMERA SNAP, CLICKED log in my btn_snap_pic on click in my customcamera class with no error. the app doesn't crash just hangs.. and if i back out of it and open the app again i get a "fail to connect to camera" i assume that this error is because when my app froze and i backed out, the camera never got released.. anyway, below is my both my CustomCamera class and my CamLayer which is my preview..
public class CustomCamera extends Activity{
String camFace ="back";
FrameLayout frame;
RelativeLayout rel;
CamLayer camPreview;
ImageView btn_snap_pic;
ImageView btn_switch_cam;
String TAG = "custom cam";
public void onCreate(Bundle savedInstanceState)
{
Bitmap btnSwitch = BitmapFactory.decodeResource(this.getResources(),
R.drawable.btn_switch_camera);
Bitmap btnSnap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.btn_take_picture);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Set Screen Orientation
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
RelativeLayout.LayoutParams buttonS = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams buttonT = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams cam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
cam.addRule(RelativeLayout.BELOW);
buttonS.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
buttonT.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
buttonT.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
try{
//Create Intance of Camera
camPreview = new CamLayer(this.getApplicationContext(),camFace);
//Relative view for everything
rel = new RelativeLayout(this);
// set as main view
setContentView(rel);
//FrameLayOut for camera
frame = new FrameLayout(this);
// add Camera to view
frame.setLayoutParams(cam);
frame.addView(camPreview);
rel.addView(frame);
btn_switch_cam = new ImageView (this);
btn_switch_cam.setImageBitmap(btnSwitch);
btn_switch_cam.setLayoutParams(buttonS);
buttonS.rightMargin = 25;
buttonS.topMargin = 25;
rel.addView(btn_switch_cam);
btn_switch_cam.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.v("CAMERA Switch", "CLICKED");
//frame.removeView(camPreview);
if(camFace.equals("front")){
camFace = "back";
}else{
camFace = "front";
}
//camPreview.stopCamera();
frame.removeView(camPreview);
restartCam();
//camPreview.switchCam(camFace);
}
});
btn_snap_pic = new ImageView(this);
btn_snap_pic.setImageBitmap(btnSnap);
btn_snap_pic.setLayoutParams(buttonT);
buttonT.rightMargin = 25;
buttonT.bottomMargin = 25;
rel.addView(btn_snap_pic);
btn_snap_pic.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.v("CAMERA Snap", "CLICKED");
camPreview.camera.takePicture(shutterCallback, rawCallback,
jpegCallback);
}
});
} catch(Exception e){}
}
public void restartCam(){
camPreview = new CamLayer(this.getApplicationContext(),camFace);
frame.addView(camPreview);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format(
"/sdcard/LC/images/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
AND THE CAMLAYER:
public class CamLayer extends SurfaceView implements SurfaceHolder.Callback {
Camera camera;
SurfaceHolder previewHolder;
String camID;
private static final String TAG = "Cam Preview";
public CamLayer(Context context, String facing)
{
super(context);
camID = facing;
previewHolder = this.getHolder();
previewHolder.addCallback(this);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
startCamera();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
Parameters params = camera.getParameters();
//params.setPreviewSize(width, height);
//params.setPictureFormat(PixelFormat.JPEG);
camera.setParameters(params);
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder arg0)
{
//camera.stopPreview();
//camera.release();
stopCamera();
}
public void onResume() {
//camera.startPreview();
startCamera();
}
public void onPause() {
// TODO Auto-generated method stub
//camera.stopPreview();
stopCamera();
}
public void switchCam(String newCamId) {
/*camera.stopPreview();
//camera.release();
if(camID.equals("front")){
camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
}else{
camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
}*/
//camera.startPreview();
//camera=Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
stopCamera();
camID = newCamId;
startCamera();
}
public void stopCamera(){
System.out.println("stopCamera method");
if (camera != null){
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
previewHolder.removeCallback(this);
previewHolder = null;
}
}
private void startCamera(){
if(camID.equals("front")){
camera=Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
}else{
camera=Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
}
try {
camera.setPreviewDisplay(previewHolder);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
//FileOutputStream outStream = null;
/*try {
//outStream = new FileOutputStream(String.format(
//"/sdcard/%d.jpg", System.currentTimeMillis()));
//outStream.write(data);
//outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: "
+ data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}*/
//CamLayer.this.invalidate();
}
});
}
catch (Throwable e){ Log.w("TAG,", "failed create surface !?!?"); }
}
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p = new Paint(Color.RED);
Log.d(TAG, "draw");
canvas.drawText("PREVIEW", canvas.getWidth() / 2,
canvas.getHeight() / 2, p);
}
}
This thread says raw is not supported
https://groups.google.com/forum/?fromgroups#!topic/android-developers/D43AdrbP9oE
A raw image would consume too much memory is my guess. Other than that, I'm also disappointed its not supported.
I am a beginner in Android development, and I have to continue a project started by a former fellow worker.
In this application we have customers files, with personal information, and there is a button allowing us to take pictures.
But here is the problem : This works fine on HTC Desire and other Android phones, but not on Galaxy S and Galaxy S II.
The algorithm used is basic : When we touch the screen or the center pad, we use the autoFocus method from the "camera" class. Then, we display the picture just taken, and when we push the menu button or the "back" button, a dialog is displayed, asking us if we want to save the picture or not.
Here is the "CameraView.java" code :
public class CameraView extends Activity implements Callback, AutoFocusCallback
{
private Camera camera;
private FrameLayout layout;
private SurfaceView surface;
private String idPatient;
private boolean start;
private int click;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(null);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
layout = new FrameLayout(this);
surface = new SurfaceView(this);
surface.getHolder().addCallback(this);
surface.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
layout.addView(surface);
setContentView(layout);
idPatient = (String) this.getIntent().getStringExtra("lePatient");
start = false;
click = 0;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER )
{
click++;
if((!start)&&(click==1))
{
camera.autoFocus(this);
return true;
}
}
if (keyCode == KeyEvent.KEYCODE_BACK )
{
finish();
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
click++;
if((!start)&&(click==1))
{
camera.autoFocus(this);
return true;
}
}
return false;
}
public void onAutoFocus(boolean success, Camera camera)
{
start = true;
PictureCallback picture = new PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
Intent intentPhoto = new Intent(CameraView.this, PhotoView.class);
intentPhoto.putExtra("lePatient", idPatient);
intentPhoto.putExtra("laPhoto", data);
CameraView.this.startActivityForResult(intentPhoto, 101);
camera.startPreview();
start = false;
click = 0;
}
};
camera.takePicture(null, null, picture);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
Camera.Parameters params = camera.getParameters();
params.setPictureFormat(PixelFormat.JPEG);
params.setPreviewSize(width, height);
camera.setParameters(params);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
try
{
camera = Camera.open();
camera.setPreviewDisplay(holder);
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
/**
* Fermeture de l'activity
*/
protected void onDestroy()
{
super.onDestroy();
}
}
And the "photoView.java" class :
public class PhotoView extends Activity
{
private static final int DIALOG_ENREGISTRER = 10;
private ImageView photo;
private byte[] data;
private String idPatient;
private DBAdapter db;
/**
* Creation de l'activity
*/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(null);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.photoview);
db = new DBAdapter(this);
db.open();
idPatient = (String) this.getIntent().getStringExtra("lePatient");
data = (byte[]) this.getIntent().getByteArrayExtra("laPhoto");
photo = (ImageView) this.findViewById(R.id.photo);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
int w = bmp.getWidth();
int h = bmp.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(90);
Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, w, h, mtx, true);
WindowManager manager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
int height= display.getHeight();
int width= display.getWidth();
Bitmap bmpFullScreen = Bitmap.createScaledBitmap(rotatedBMP, width, height, true);
photo.setImageBitmap(bmpFullScreen);
}
/**
* Permet de récuperer un évènement de click de touche
*/
public boolean onKeyUp(int keyCode, KeyEvent event) {
if((keyCode==KeyEvent.KEYCODE_BACK) ||(keyCode==KeyEvent.KEYCODE_MENU))// zoom in
{
showDialog(DIALOG_ENREGISTRER);
}
//return super.onKeyUp(keyCode, event);
return false;
}
/**
* Permet de créer des boites de dialog
*/
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DIALOG_ENREGISTRER:
return new AlertDialog.Builder(PhotoView.this)
.setIcon(android.R.drawable.ic_menu_info_details)
.setTitle("Enregistrer ?")
.setPositiveButton("OUI", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String title = PhotoView.this.savePhotoDB();
PhotoView.this.savePhotoFS(title);
finish();
}
})
.setNegativeButton("NON", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
finish();
}
})
.create();
}
return null;
}
/**
* Permet de sauvegarder une photo dans la base de données
* #param title
*/
private String savePhotoDB()
{
Log.i("","idPatient : " +idPatient);
String comment = "Note : ";
Log.i("","comment : " + comment);
Date maintenant = new Date(System.currentTimeMillis());
SimpleDateFormat formatDateJour = new SimpleDateFormat("yyyyddMM");
String date = formatDateJour.format(maintenant);
Log.i("","Date formatée : " + date);
SimpleDateFormat formatHeure = new SimpleDateFormat("mmss");
String heure = formatHeure.format(maintenant);
Log.i("","Heure formatée : " + heure);
String fileName = "photo"+date+heure+".jpeg";
Log.i("","fileName : " + fileName);
String title = "photo"+date+heure+".jpeg";
Log.i("","title : " + title);
String userDefined = "1";
Log.i("","userDefined : " + userDefined);
db.insererPhoto(idPatient, comment, date, fileName, title, userDefined);
return title;
}
/**
* Permet de sauvegarder une photo sur le file system
* #param title
*/
private void savePhotoFS(String title) {
try
{
File fs = new File(PhotoView.this.getFilesDir()+"/"+title);
FileOutputStream fos = new FileOutputStream(fs);
fos.write(data);
fos.flush();
fos.close();
//Toast.makeText(PhotoView.this, ""+fs.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Fermeture de l'activity
*/
protected void onDestroy()
{
db.close();
super.onDestroy();
}
}
Can anyone help me please ?
Thanks for reading :)
thank you for your answer.
Problem solved !
Here is the answer for anyone who have the same problem :
In these lines :
Intent intentPhoto = new Intent(CameraView.this, PhotoView.class);
intentPhoto.putExtra("lePatient", idPatient);
intentPhoto.putExtra("laPhoto", data);
startActivityForResult(intentPhoto, 101);
The "intentPhoto.putExtra("laPhoto", data)" method can't be executed because the "data" size is too big. "data" contains the picture taken, and on Galaxy SII, the picture resolution is very big, so this method can't send data (because it's size limited).
So I just used the setPictureSize(width, height) method (Camera.Parameters) on surfaceChanged method to define my own resolution (1024x768), and now it's works fine !
Careful : Before define your own resolution, you HAVE TO verify that it's accepted by your device by using getSupportedPictureSizes() method
Hope this could help someone
Below is the code I used to do the same thing you are trying to do. It creates a SurfaceView and starts the camera preview. Upon tapping anywhere on the screen it takes a picture, shows it and displays two buttons - save and retry (see the onPictureTaken method). The user can click Save, and return the data back to the app, or retry (which from what I can tell I did not finish the retry functionality - it just calls finish()). Hope this helps.
public class SnapShot extends Activity implements OnClickListener,
SurfaceHolder.Callback, Camera.PictureCallback {
SurfaceView cameraView;
SurfaceHolder surfaceHolder;
Camera camera;
LayoutInflater inflater;
Uri imageFileUri;
Button save;
Button retry;
View viewControl;
LayoutParams layoutParamsControl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_camera);
cameraView = (SurfaceView) this.findViewById(R.id.CameraView);
surfaceHolder = cameraView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);
cameraView.setFocusable(true);
cameraView.setFocusableInTouchMode(true);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
inflater = LayoutInflater.from(getBaseContext());
viewControl = inflater.inflate(R.layout.camera_control, null);
save = (Button) viewControl.findViewById(R.id.vc_btn_keep);
retry = (Button)viewControl.findViewById(R.id.vc_btn_discard);
layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
camera.startPreview();
}
public void surfaceCreated(SurfaceHolder holder) {
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();
Log.v("surfaceCreated", exception.getMessage());
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
this.addContentView(viewControl, layoutParamsControl);
save.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
insertImage(data);
Intent i = new Intent();
i.putExtra("data", imageFileUri.toString());
setResult(-1, i);
finish();
}});
retry.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
}
public void insertImage(byte[] data)
{
Bitmap b = null;
try {
b = GeneralUtils.decodeFile(data, this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
//b = null;
Bitmap bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
Matrix m = new Matrix();
if (b.getWidth() > b.getHeight())
{
m.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
String result = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
b.recycle();
data = null;
b = null;
m = null;
imageFileUri = Uri.parse(result);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(null, null, null, this);
}
}