i have created custom camera app,
for now its captures image and displayed in imageView.
what i want is video capturing. how can i
how achieve with this same surfaceView
when swipe from left or right
please help me
Code
PreviewDemo.java
package com.example.newcam;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class PreviewDemo extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;;
private String imageFilePath;
private Button buttonStartCameraPreview, buttonStopCameraPreview;
private ImageView showImageView;
private List<Camera.Size> mSupportedPreviewSizes;
private Camera.Size mPreviewSize;
static final int REQUEST_VIDEO_CAPTURE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview);
buttonStartCameraPreview = (Button) findViewById(R.id.start);
// buttonStopCameraPreview = (Button) findViewById(R.id.stop);
showImageView = (ImageView) findViewById(R.id.imageView1);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.surface);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
buttonStartCameraPreview
.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(null, null, jpegCallback);
}
});
showImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent openImageInGallery = new Intent();
openImageInGallery.setAction(Intent.ACTION_VIEW);
openImageInGallery.setDataAndType(
Uri.parse("file://" + imageFilePath), "image/*");
startActivity(openImageInGallery);
}
});
surfaceView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.autoFocus(new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean focus_flag, Camera cam) {
}
});
}
});
}
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
File miDirs = new File(
Environment.getExternalStorageDirectory() + "/myphotos");
if (!miDirs.exists())
miDirs.mkdirs();
final Calendar c = Calendar.getInstance();
String new_Date = c.get(Calendar.DAY_OF_MONTH) + "-"
+ ((c.get(Calendar.MONTH)) + 1) + "-"
+ c.get(Calendar.YEAR) + " " + c.get(Calendar.HOUR)
+ "-" + c.get(Calendar.MINUTE) + "-"
+ c.get(Calendar.SECOND);
imageFilePath = String.format(
Environment.getExternalStorageDirectory() + "/myphotos"
+ "/%s.jpg", "DICM_" + new_Date);
Uri selectedImage = Uri.parse(imageFilePath);
File file = new File(imageFilePath);
String path = file.getAbsolutePath();
Bitmap bitmap = null;
outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
if (path != null) {
if (path.startsWith("content")) {
bitmap = decodeStrem(file, selectedImage,
PreviewDemo.this);
} else {
bitmap = decodeFile(file, 10);
}
}
if (bitmap != null) {
showImageView.setImageBitmap(bitmap);
// Toast.makeText(MainActivity.this,"Picture Captured Successfully:",
// Toast.LENGTH_LONG).show();
camera.startPreview();
} else {
Toast.makeText(PreviewDemo.this,
"Failed to Capture the picture. kindly Try Again:",
Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
};
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w,
int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) h / w;
if (sizes == null)
return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public static Bitmap decodeFile(File f, int sampling) {
try {
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inJustDecodeBounds = true;
BitmapFactory.decodeStream(
new FileInputStream(f.getAbsolutePath()), null, o2);
o2.inSampleSize = sampling;
o2.inTempStorage = new byte[48 * 1024];
o2.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(
new FileInputStream(f.getAbsolutePath()), null, o2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bitmap = rotateImage(bitmap, f.getAbsolutePath());
return bitmap;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
return null;
}
public static Bitmap rotateImage(Bitmap bmp, String imageUrl) {
if (bmp != null) {
ExifInterface ei;
int orientation = 0;
try {
ei = new ExifInterface(imageUrl);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
e.printStackTrace();
}
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_UNDEFINED:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
bmpHeight, matrix, true);
return resizedBitmap;
} else {
return bmp;
}
}
public static Bitmap decodeStrem(File fil, Uri selectedImage,
Context mContext) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(mContext.getContentResolver()
.openInputStream(selectedImage));
final int THUMBNAIL_SIZE = getThumbSize(bitmap);
bitmap = Bitmap.createScaledBitmap(bitmap, THUMBNAIL_SIZE,
THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos
.toByteArray()));
return bitmap = rotateImage(bitmap, fil.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
public static int getThumbSize(Bitmap bitmap) {
int THUMBNAIL_SIZE = 2000;
if (bitmap.getWidth() < 300) {
THUMBNAIL_SIZE = 250;
} else if (bitmap.getWidth() < 600) {
THUMBNAIL_SIZE = 500;
} else if (bitmap.getWidth() < 1000) {
THUMBNAIL_SIZE = 750;
} else if (bitmap.getWidth() < 2000) {
THUMBNAIL_SIZE = 1500;
} else if (bitmap.getWidth() < 4000) {
THUMBNAIL_SIZE = 2000;
} else if (bitmap.getWidth() > 4000) {
THUMBNAIL_SIZE = 2000;
}
return THUMBNAIL_SIZE;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setPreviewSize(580, 960);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
int camcount = 0;
try {
camera = Camera.open();
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
}
}
layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.view.SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
<Button
android:id="#+id/start"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_white" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp" />
<Button
android:id="#+id/video"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="27dp"
android:background="#drawable/btn_white_video" />
</RelativeLayout>
</RelativeLayout>
Related
I am making camera app but when i m running it it shows unfortunately app has stopped.In the code it shows no error but still its not working so help me with it.
the below code is the main code of the app and contains the captured image saving file
package com.example.cam;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;
public class CamTestActivity extends Activity {
private static final String TAG = "CamTestActivity";
Preview preview;
Button buttonClick;
Camera camera;
Activity act;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
act = this;
setContentView(R.layout.main);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
((FrameLayout) findViewById(R.id.layout)).addView(preview);
preview.setKeepScreenOn(true);
preview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Toast.makeText(ctx,getString(R.string.take_photo_help), Toast.LENGTH_LONG).show();
buttonClick = (Button) findViewById(R.id.btnCapture);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
preview.mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
buttonClick.setOnLongClickListener(new View.OnLongClickListener(){
#Override
public boolean onLongClick(View arg0) {
camera.autoFocus(new Camera.AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
return true;
}
});
}
#Override
protected void onResume() {
super.onResume();
int numCams = Camera.getNumberOfCameras();
if(numCams > 0){
try{
camera = Camera.open(0);
camera.startPreview();
preview.setCamera(camera);
} catch (RuntimeException ex){
Toast.makeText(ctx, getString(R.string.camera_not_found), Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onPause() {
if(camera != null) {
camera.stopPreview();
preview.setCamera(null);
camera.release();
camera = null;
}
super.onPause();
}
private void resetCam() {
camera.startPreview();
preview.setCamera(camera);
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SaveImageTask().execute(data);
resetCam();
Log.d(TAG, "onPictureTaken - jpeg");
}
};
#SuppressLint("StaticFieldLeak")
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
}
hear the preview code and contains preview after capturing the photo
package com.example.cam;
/*
* #author Jose Davis Nidhin
*/
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
Preview(Context context, SurfaceView sv) {
super(context);
mSurfaceView = sv;
addView(mSurfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
// get Camera parameters
Camera.Parameters params = mCamera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
mCamera.setParameters(params);
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
child.layout((width - scaledChildWidth) / 2, 0,
(width + scaledChildWidth) / 2, height);
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight) / 2,
width, (height + scaledChildHeight) / 2);
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
if (mCamera != null) {
mCamera.stopPreview();
}
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if(mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
}
this is the crash log
I/InstantRun: starting instant run server: is main process
D/AccessibilityManager: getInstance() new sInstance = android.view.accessibility.AccessibilityManager#4ed699a, context = com.example.cam.CamTestActivity#65f12cb, userId = 0
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cam, PID: 3386
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cam/com.example.cam.CamTestActivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5452)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at com.android.internal.policy.PhoneWindow.requestFeature(PhoneWindow.java:326)
at android.app.Activity.requestWindowFeature(Activity.java:3656)
at com.example.cam.CamTestActivity.onCreate(CamTestActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2477)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1345)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5452)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:762)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
I/Process: Sending signal. PID: 3386 SIG: 9
Application terminated.
now please help me solving the problem
Enable different permissions at a single time on app startup in android programmatically.
Here you need to add only CAMERA permission for above Marshmallow Devices, Add this code before Starting your Camera Screen
References :https://www.android-examples.com/request-check-multiple-runtime-permissions-android-marshmallow/
<uses-permission android:name="android.permission.CAMERA"/>
MainActivity.java Code :
public class MainActivity extends AppCompatActivity {
Button button;
public static final int RequestPermissionCode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermission()){
Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
}
else {
requestPermission();
}
}
});
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{
CAMERA,
}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean CameraPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (CameraPermission ) {
Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int FirstPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
return FirstPermissionResult == PackageManager.PERMISSION_GRANTED ;
}
}
Or, If you to check Manually without using this Code, its just for check :
Go to Settings -> Apps -> Select Your App -> tap on permissions -> enable Camera Permission.
In your CamTestActivity, move the line requestWindowFeature(Window.FEATURE_NO_TITLE) so it appears before super.onCreate(savedInstanceState)
please help me
i'm create app camera with orientation portrait, but the preview camera is not full size to screen, what's wrong?
this is my class:
CameraPreview.class
package com.dm.zbar.android.scanner;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Build;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import java.io.IOException;
import java.util.List;
class CameraPreview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "CameraPreview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize, mPictureSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
PreviewCallback mPreviewCallback;
AutoFocusCallback mAutoFocusCallback;
CameraPreview(Context context, PreviewCallback previewCallback, AutoFocusCallback autoFocusCb) {
super(context);
mPreviewCallback = previewCallback;
mAutoFocusCallback = autoFocusCb;
mSurfaceView = new SurfaceView(context);
addView(mSurfaceView);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
child.layout((width - scaledChildWidth) / 2, 0,
(width + scaledChildWidth) / 2, height);
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight) / 2,
width, (height + scaledChildHeight) / 2);
}
}
}
public void hideSurfaceView() {
mSurfaceView.setVisibility(View.INVISIBLE);
}
public void showSurfaceView() {
mSurfaceView.setVisibility(View.VISIBLE);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
if (mCamera != null) {
mCamera.cancelAutoFocus();
mCamera.stopPreview();
}
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (holder.getSurface() == null){
// preview surface does not exist
return;
}
if (mCamera != null) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
if(getResources().getConfiguration().orientation== getResources().getConfiguration().ORIENTATION_LANDSCAPE){
mCamera.setDisplayOrientation(0);
}else{
mCamera.setDisplayOrientation(90);
}
requestLayout();
mCamera.setParameters(parameters);
mCamera.setPreviewCallback(mPreviewCallback);
mCamera.startPreview();
mCamera.autoFocus(mAutoFocusCallback);
}
}
}
and this my capture:
http://postimg.org/image/hrrmrto3f/
http://postimg.org/image/obgq3g9vp/
I guess your .xml is incorrect:Replace your xml with this one:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/top_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/dashboard_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textSize="16sp"
android:text="Front of the card"
android:textColor="#8f928c" />
</RelativeLayout>
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/btn_area"
android:layout_below="#+id/top_bar" />
<LinearLayout
android:id="#+id/btn_area"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_vertical"
android:layout_margin="5dp"
android:paddingBottom="3.5dp"
android:layout_alignParentBottom="true" >
<Button
android:id="#+id/button_preview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:enabled="false"
android:textSize="18sp"
android:text="Refresh" />
<Button
android:id="#+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:enabled="false"
android:textSize="18sp"
android:text="Capture" />
<Button
android:id="#+id/button_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:textSize="18sp"
android:text="Ok" />
</LinearLayout>
</RelativeLayout>
Your CameraActivity.java
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
public class CameraActivity extends Activity {
private Camera mCamera;
private CustomizeCameraPreview mPreview;
public static final int MEDIA_TYPE_IMAGE = 1;
Button captureButton;
Button previewButton;
Button viewButton;
String pictureFilePath = null;
FrameLayout preview;
TextView tvheader;
//addition for free-hand drawing
Drawing mv = null;
int color_code = 0xFFFF2525;
ImageView colorButton;
ImageView undo;
boolean startDraw = false;
String str="";
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("CameraActivity", "Error creating media file, check storage permissions");
return;
}
initDrawing(scale_and_rotateImage(data,480));
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customcamera);
//str=getIntent().getExtras().getString("cardimage");
try{
str=getIntent().getStringExtra("cardimage");
System.out.println("str==="+str);
tvheader=(TextView)findViewById(R.id.dashboard_logo);
if(str.equals("front"))
tvheader.setText("Front of the card");
else
tvheader.setText("Back of the card");
}catch(Exception e)
{
e.printStackTrace();
}
startDraw = true;
}
#Override
public void onResume() {
// 31-Jul-2013 ///////////////////
preview = (FrameLayout) findViewById(R.id.camera_preview);
// Add a listener to the Preview button
previewButton = (Button) findViewById(R.id.button_preview);
captureButton = (Button) findViewById(R.id.button_capture);
viewButton = (Button) findViewById(R.id.button_view);
if(checkCameraHardware(getApplicationContext())) {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
mCamera = getCameraInstance();
flashLightOn(mCamera);
// Create our Preview view and set it as the content of our activity.
mPreview = new CustomizeCameraPreview(getApplicationContext(), mCamera);
preview.addView(mPreview);
previewButton.setEnabled(false);
captureButton.setEnabled(true);
viewButton.setEnabled(false);
}
previewButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
startDraw = true;
// release previous camera instance
if (mCamera != null) {
mCamera.stopPreview();
preview.removeView(mPreview);
mCamera.release();
mCamera = null;
}
if(mPreview != null) mPreview = null;
// Create an instance of Camera
mCamera = getCameraInstance();
flashLightOn(mCamera);
// Create our Preview view and set it as the content of our activity.
mPreview = new CustomizeCameraPreview(getApplicationContext(), mCamera);
preview.addView(mPreview);
v.setEnabled(false);
captureButton.setEnabled(true);
viewButton.setEnabled(false);
}
}
);
// Add a listener to the Capture button
captureButton.setOnClickListener (
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
try {
mCamera.takePicture(null, null, mPicture);
previewButton.setEnabled(true);
v.setEnabled(false);
viewButton.setEnabled(true);
}catch(Exception e) {
//mCamera not instantiated
}
}
}
);
// Add a listener to the View button
viewButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// return image path to calling activity
pictureFilePath = saveImage();
if(pictureFilePath != null) {
Intent data = new Intent();
//---set the data to pass back---
data.setData(Uri.parse(pictureFilePath));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
previewButton.setEnabled(true);
captureButton.setEnabled(false);
//v.setEnabled(false);
}
}
);
//////////////////////////////////
super.onResume();
}
public String saveImage() {
pictureFilePath = null;
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("CameraActivity", "Error creating media file, check storage permissions");
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
Bitmap tmp = mv.getDrawingCache();
tmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
pictureFilePath = pictureFile.getAbsolutePath();
} catch (Exception e) {
Log.d("CameraActivity", "Error accessing file: " + e.getMessage());
}
return pictureFilePath;
}
/** 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;
}
}
public void flashLightOn(Camera cam) {
try {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_AUTO);
cam.setParameters(p);
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Exception flashLightOn()", Toast.LENGTH_SHORT).show();
}
}
/** 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
c.setDisplayOrientation(90);
//context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** 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");
*/
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "canberra trailpass");
// 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("canberra trailpass", "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 {
return null;
}
return mediaFile;
}
private Bitmap scale_and_rotateImage(byte[] input, int dstWidth)
{
// code to free some memory
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
// create the blank bitmap
Bitmap inputImage = BitmapFactory.decodeByteArray(input, 0, input.length, opts); // java.lang.OutOfMemoryError error
// create the smaller bitmap
inputImage = null;
opts.inJustDecodeBounds = false;
opts.inSampleSize = (int) opts.outWidth / dstWidth;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
inputImage = BitmapFactory.decodeByteArray(input, 0, input.length, opts);
// create a matrix for the manipulation
Matrix m = new Matrix();
//int width = inputImage.getWidth();
//int height = inputImage.getHeight();
int width = opts.outWidth;
int height = opts.outHeight;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) dstWidth) / width;
//float scaleHeight = ((float) dstHeight) / height;
// resize the bit map
m.postScale(scaleWidth, scaleWidth);
// rotate the Bitmap
m.postRotate(90);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(inputImage, 0, 0,
width, height, m, true);
inputImage.recycle();
inputImage = null;
/*
ByteArrayOutputStream blob = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, blob);
resizedBitmap.recycle();
resizedBitmap = null;
return blob.toByteArray();
*/
return resizedBitmap;
}
#Override
public void onBackPressed(){
Intent data = new Intent();
//---set the data to pass back---
//data.setData(null);
System.out.println("--> Back from camera activity");
setResult(RESULT_CANCELED, data);
finish();
super.onBackPressed();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
preview.removeView(mPreview);
super.onPause();
}
public void initDrawing(Bitmap resizedBitmap) {
int line_width = (int) this.getResources().getInteger(R.integer.line_width);
mv = new Drawing(this,line_width,color_code,1);
mv.setDrawingCacheEnabled(true);
//mv.setBackground(new BitmapDrawable(resizedBitmap));
mv.setBackgroundDrawable(new BitmapDrawable(getResources(), resizedBitmap));
preview.addView(mv);
LinearLayout bt_container = new LinearLayout(this);
bt_container.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
bt_container.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(5, 2, 5, 2);
undo = new ImageView(this);
undo.setImageResource(R.drawable.undo_icon);
bt_container.addView(undo,layoutParams);
undo.setVisibility(View.GONE);
undo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mv.onClickUndo();
}
});
/* colorButton = new ImageView(this);
//colorButton.setImageResource(R.drawable.pencil1); changed on 25-Nov-13
colorButton.setBackgroundColor(color_code);
colorButton.setImageResource(R.drawable.pencil2);
bt_container.addView(colorButton,layoutParams);
colorButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AmbilWarnaDialog dialog = new AmbilWarnaDialog(CameraActivity.this, color_code, new OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
startDraw = true;
color_code = color;
mv.setColor(color_code);
colorButton.setBackgroundColor(color_code);
colorButton.setImageResource(R.drawable.pencil2);
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
}
});
dialog.show();
}
});*/
FrameLayout.LayoutParams fParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.RIGHT | Gravity.TOP);
preview.addView(bt_container, fParams);
}
public class Drawing extends View {
private Paint mPaint, mBitmapPaint;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Context mContext;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private int color, size, state;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Integer> colors = new ArrayList<Integer>();
private ArrayList<Integer> sizes = new ArrayList<Integer>();
public Drawing(Context c) {
super(c);
mContext = c;
}
public Drawing(Context c, int size, int color, int state) {
super(c);
mContext = c;
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(size);
setColor(color);
setSize(size);
setState(state);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
if(!startDraw) return;
for (int i = 0; i < paths.size(); i++) {
mPaint.setColor(colors.get(i));
mPaint.setStrokeWidth(sizes.get(i));
canvas.drawPath(paths.get(i), mPaint);
}
mPaint.setColor(color);
canvas.drawPath(mPath, mPaint);
}
public void setColor(int color) {
this.color = color;
mPaint.setColor(color);
}
public void setSize(int size) {
this.size = size;
}
public void setState(int state) {
this.state = state;
paths.clear();
sizes.clear();
colors.clear();
invalidate();
mPaint.setXfermode(null);
//mPaint.setAlpha(0xFF);
mPaint.setStrokeWidth(size);
}
public void clearCanvas() {
mBitmap.eraseColor(Color.TRANSPARENT);
paths.clear();
sizes.clear();
colors.clear();
mPath.reset();
invalidate();
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
sizes.remove(sizes.size() - 1);
colors.remove(colors.size() - 1);
if(colors.size() > 0)
undo.setBackgroundColor(colors.get(colors.size() - 1));
else
undo.setVisibility(View.GONE);
invalidate();
}
}
private void touch_start(float x, float y) {
undo.setVisibility(View.VISIBLE);
undo.setBackgroundColor(color);
undonePaths.clear();
mPath.reset();
//colors.add(color);
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
if(state != 0) {
colors.add(color);
sizes.add(size);
paths.add(mPath);
mPath = new Path();
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(!startDraw) return false;
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
}
and I cant find any mistake in your CameraPreview.java
The output will be like below:
It works fine for me. Add this into mainactivity:
mPreview = new CamLayer(this);
Splash.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if (mPreview == null) {
mPreview = new CamLayer(MainActivity.this);
}
mPreview.setcameraparam(flash);
Intent i = new Intent(MainActivity.this, ShowingImage.class);
mPreview.getimage(MainActivity.this, i);
}
});
Then in your public classCamLayer extends SurfaceView implements SurfaceHolder.Callback class, add these methods:
public void getimage(final Context context,final Intent i) {
final File pictureFile = getOutputMediaFile();
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
i.putExtra("file_path", pictureFile.getPath());
context.startActivity(i);
} catch (FileNotFoundException e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
};
mCamera.takePicture(null, null, mPicture);
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Sunil2");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
public void setcameraparam(String param) {
Parameters parameter = mCamera.getParameters();
parameter.setFlashMode(param);
mCamera.setParameters(parameter);
}
and showing image class after intent:
public class ShowingImage extends Activity {
#SuppressLint("NewApi")
Bitmap myBitmap;
int width;
int height;
private float curScale = 1F;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show_image);
Intent intent = getIntent();
String path = intent.getStringExtra("file_path");
Log.e("file store in ", "" + path);
File imgFile = new File(path);
if (imgFile.exists()) {
ImageView myImage = (ImageView) findViewById(R.id.imageView1);
myBitmap = BitmapFactory.decodeFile(path);
width = myBitmap.getWidth();
height = myBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(curScale, curScale);
matrix.postRotate(90);
Bitmap resizedBitmap = Bitmap.createBitmap(myBitmap, 0, 0, width,
height, matrix, true);
myImage.setImageBitmap(resizedBitmap);
} else {
Toast.makeText(getApplicationContext(), "file not exist", 1000)
.show();
}
}
}
xml:
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Surface along with image when i click on button it's save only the surface for this i tried
following code
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
ShutterCallback shutterCallback = new ShutterCallback()
{
public void onShutter()
{
Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
try
{
File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"Camera");
if (!root.exists())
{
root.mkdirs();
}
FileOutputStream f = new FileOutputStream(new File(root,System.currentTimeMillis()+".jpg"));
int len1 = data.length;
f.write(data,0, len1);
f.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
}
}
};
by this code getting only surface, is there any possible to save surface along with image ?
if any one knows please help me
You try using this example . Such as
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class FingerpaintView extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "FingerpaintView";
private Paint foregroundPaint;
private Paint backgroundPaint;
private int width, height;
private int lastTouchX, lastTouchY;
private Bitmap pictureBitmap;
private Canvas pictureCanvas;
private final Context context;
public FingerpaintView(Context context) {
super(context);
this.context=context;
init();
}
public FingerpaintView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
init();
}
private void init() {
setFocusableInTouchMode(true);
getHolder().addCallback(this);
foregroundPaint = new Paint();
foregroundPaint.setColor(Color.WHITE);
foregroundPaint.setStrokeWidth(4);
backgroundPaint = new Paint();
backgroundPaint.setColor(Color.BLACK);
lastTouchX = -1;
lastTouchY = -1;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
final int x = (int) event.getX();
final int y = (int) event.getY();
if ((event.getAction() == MotionEvent.ACTION_DOWN) || (event.getAction() == MotionEvent.ACTION_MOVE)) {
Log.d(TAG, "Touched " + x + "," + y);
if ((lastTouchX != -1) && (lastTouchY != -1)) {
pictureCanvas.drawLine(lastTouchX, lastTouchY, x, y, foregroundPaint);
draw();
}
lastTouchX = x;
lastTouchY = y;
} else {
lastTouchX = -1;
lastTouchY = -1;
}
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU){
clear();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
this.width = width;
this.height = height;
if (pictureBitmap != null) {
pictureBitmap.recycle();
}
pictureBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
pictureCanvas = new Canvas(pictureBitmap);
clear();
draw();
}
public void draw() {
final Canvas c = getHolder().lockCanvas();
if (c != null) {
c.drawBitmap(pictureBitmap, 0, 0, null);
getHolder().unlockCanvasAndPost(c);
}
}
public void clear() {
pictureCanvas.drawRect(0, 0, width, height, backgroundPaint);
draw();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (pictureBitmap != null) {
saveFile(pictureBitmap,"MyImage");
pictureBitmap.recycle();
}
pictureBitmap = null;
}
private void saveFile(Bitmap bitmap, String name) {
// String filename = String.valueOf(System.currentTimeMillis()) ;
String extStorageDirectory;
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
final File file = new File(extStorageDirectory, name);
try {
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(context, "Saved", Toast.LENGTH_LONG).show();
} catch (final FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
I expected you will be helpful.
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpeg", System.currentTimeMillis()));
I'm trying to save an image from the camera onto the phone. I'm able to take the picture, see the taken picture on the SurfaceView and everything, but when I go to my phone's filesystem, the picture is nowhere to be found. I'm thinking it's this specific line of code, however I will post my entire Activity just to be sure.
package com.commonsware.android.skeleton;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.*;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
// ----------------------------------------------------------------------
public class SimpleBulbActivity extends Activity {
private Preview mPreview;
private static final String TAG = "CameraDemo";
FrameLayout preview;
Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
}
protected void onResume() {
super.onResume();
//Setup the FrameLayout with the Camera Preview Screen
mPreview = new Preview(this);
preview = (FrameLayout)findViewById(R.id.preview);
preview.addView(mPreview);
}
public void snap(View view) {
mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] _data, Camera _camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera _camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream =
// CameraDemo.this.openFileOutput(String.format("%d.jpg",
// System.currentTimeMillis()), 0);
// Or write to sdcard
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpeg", System.currentTimeMillis()));
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
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");
}
};
// ----------------------------------------------------------------------
class Preview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(Environment.getExternalStorageDirectory().toString());
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: "
+ data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
mCamera.release();
mCamera = null;
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.05;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, w, h);
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if(display.getRotation() == Surface.ROTATION_0)
{
parameters.setPreviewSize(optimalSize.height, optimalSize.width);
mCamera.setDisplayOrientation(90);
}
if(display.getRotation() == Surface.ROTATION_90)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
}
if(display.getRotation() == Surface.ROTATION_180)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
}
if(display.getRotation() == Surface.ROTATION_270)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
mCamera.setDisplayOrientation(0);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
}
do you have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in your AndroidManifest.xml?
EDIT: As Oren Bengigi suggested, I tried enclosing the bit of code that saves the data in a post(Runnable), but I'm still getting the same results:
final Handler handler = new Handler();
void savePicture(final byte[] data) {
handler.post(new Runnable() {
public void run() {
try {
FrameLayout view = (FrameLayout)findViewById(R.id.image);
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
b.compress(CompressFormat.PNG, 50, new FileOutputStream(Environment.getExternalStorageDirectory() + String.format(
"/SimpleBulb/%d.png", System.currentTimeMillis())));
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
});
}
I am trying to take a picture with an overlay and save both as one .png. I am able to save the image the camera captures, and I'm able to save the overlay, but when I try to save both as one image, I only see the overlay and a black background. I've switched the two layers and the entire image was black, so the picture from the camera is just being rendered black. Any help on this would be GREATLY appreciated. Here's my code:
package com.commonsware.android.skeleton;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.*;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
// ----------------------------------------------------------------------
public class SimpleBulbActivity extends Activity {
private Preview mPreview;
private static final String TAG = "CameraDemo";
RelativeLayout preview;
Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// create a File object for the parent directory
File imageDirectory = new File(Environment.getExternalStorageDirectory() + "/SimpleBulb/");
// Check if the directory exists
if(!imageDirectory.exists()) {
// have the object build the directory structure, if needed.
imageDirectory.mkdirs();
}
setContentView(R.layout.main);
}
protected void onResume() {
super.onResume();
//Setup the FrameLayout with the Camera Preview Screen
mPreview = new Preview(this);
preview = (RelativeLayout)findViewById(R.id.preview);
preview.addView(mPreview);
}
public void snap(View view) {
mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] _data, Camera _camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera _camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream =
// CameraDemo.this.openFileOutput(String.format("%d.jpg",
// System.currentTimeMillis()), 0);
// Save image to SD Card
/*BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 5;
String filename = Environment.getExternalStorageDirectory() + String.format(
"/SimpleBulb/%d.png", System.currentTimeMillis());
Bitmap myImage = BitmapFactory.decodeByteArray(data, 0,data.length,options);
outStream = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(outStream);
myImage.compress(CompressFormat.PNG, 95, bos);
bos.flush();
bos.close();
// Replace view with Picture taken
ImageView cameraImage = (ImageView)findViewById(R.id.taken_image);
cameraImage.setImageBitmap(myImage);*/
// Save as one
FrameLayout view = (FrameLayout)findViewById(R.id.image);
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
b.compress(CompressFormat.PNG, 50, new FileOutputStream(Environment.getExternalStorageDirectory() + String.format(
"/SimpleBulb/%d.png", System.currentTimeMillis())));
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
// ----------------------------------------------------------------------
class Preview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
Log.d(TAG, "onPreviewFrame - wrote bytes: "
+ data.length);
Preview.this.invalidate();
}
});
} catch (IOException e) {
mCamera.release();
mCamera = null;
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.05;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, w, h);
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if(display.getRotation() == Surface.ROTATION_0)
{
parameters.setPreviewSize(optimalSize.height, optimalSize.width);
mCamera.setDisplayOrientation(90);
}
if(display.getRotation() == Surface.ROTATION_90)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
}
if(display.getRotation() == Surface.ROTATION_180)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
}
if(display.getRotation() == Surface.ROTATION_270)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
mCamera.setDisplayOrientation(0);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
}
Here's my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/layout">
<FrameLayout android:id="#+id/image" android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout android:id="#+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
<RelativeLayout android:id="#+id/bulb_pic" android:layout_width="match_parent" android:layout_height="112dip">
<ImageView android:id="#+id/bulb" android:src="#drawable/litbulb"
android:layout_width="match_parent"
android:layout_height="112dip" />
</RelativeLayout>
</FrameLayout>
<Button android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/buttonClick"
android:text="Snap!" android:layout_gravity="center" android:onClick="snap"></Button>
</LinearLayout>
It might be that the ImageView that you set, doesn't update immediately.
What I would try is running the follwoing code:
Bitmap b = view.getDrawingCache();
b.compress(CompressFormat.PNG, 50, new FileOutputStream(Environment.getExternalStorageDirectory() + String.format(
"/SimpleBulb/%d.png", System.currentTimeMillis())));
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
in a handler with postRunaable and see if it works.