Below is the code for a custom camera app I'm working on. Everthing works fine, except when the images are taken with flash on. With flash on, the preview showed to the user to accept the image looks right, but the image saved to the sdcard is very dark (with only white objects slightly visible) and often just black. I've been trying to figure out the problem for days now. Any ideas what might be going on?
public class CustomCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
Surfaceview surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
...
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
Camera.Parameters parameters = camera.getParameters();
camera.setDisplayOrientation(90);
determineDisplayOrientation();
camera.setPreviewDisplay(surfaceHolder);
previewing = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
List<String> supportedFocusModes = parameters.getSupportedFocusModes();
if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else{
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
}
if (parameters.getSupportedWhiteBalance().contains(
Parameters.WHITE_BALANCE_AUTO)) {
parameters.setWhiteBalance(Parameters.WHITE_BALANCE_AUTO);
}
if (parameters.getSupportedSceneModes().contains(
Parameters.SCENE_MODE_AUTO)) {
parameters.setSceneMode(Parameters.SCENE_MODE_AUTO);
}
camera.setParameters(parameters);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
flashButton.setBackgroundResource(R.drawable.auto_flash);
camera = Camera.open(CURRENT_CAMERA_ID);
Camera.Parameters camParameters = camera.getParameters();
flashSupported = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if ( flashSupported){
camParameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
lastFlashMode = AUTO_FLASH;
camera.setParameters(camParameters);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
//click listener for button to take picture
public void takePicture(View view){
if (camera != null){
orientationListener.rememberOrientation();
camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
showPicPreviewScreen();
}
}
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback() {
#Override
public void onShutter() {
}
};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
}
};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
int rotation = (displayOrientation + orientationListener.getRememberedOrientation() + layoutOrientation) % 360;
if (rotation != 0){
Log.e("rotaion", "not 0, rotating");
Bitmap oldBitmap = bitmapPicture;
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
bitmapPicture = Bitmap.createBitmap(bitmapPicture, 0, 0, bitmapPicture.getWidth(), bitmapPicture.getHeight(), matrix, false);
oldBitmap.recycle();
}
camera.stopPreview();
previewing = false;
ImageSaver imageSaver = new ImageSaver();
imageSaver.saveImage(getApplicationContext(), bitmapPicture);
}
};
}
And here's the class that saves the image
public class ImageSaver{
private Context context;
private String NameOfFolder = "/ProjectFolder";
String fileName;
String file_path;
public void saveImage(Context context,Bitmap ImageToSave){
context = context;
file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+ NameOfFolder;
String CurrentDateAndTime= getCurrentDateAndTime();
File dir = new File(file_path);
if(!dir.exists()){
dir.mkdirs();
}
fileName = CurrentDateAndTime+ ".jpg";
File file = new File(dir, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
ImageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fOut); //85
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e) {UnableToSave();}
catch (IOException e){UnableToSave();}
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
}
}
Thanks a lot!
Related
I am trying to record a video in background through Service but my code creates and empty video file everytime and not returning any error as well.
Below is my Service class:
public class BackGroundVideoRecorder extends Service implements SurfaceHolder.Callback {
private static final String LOG_TAG = "BackGroundVideoRecorder";
private MediaRecorder mediaRecorder = null;
private WindowManager windowManager;
private SurfaceView surfaceView;
private Camera camera = null;
#Override
public void onCreate() {
// Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT
);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
camera = Camera.open(1);
mediaRecorder = new MediaRecorder();
camera.unlock();
//mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setCamera(camera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoSize(320, 480);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
String out = Environment.getExternalStorageDirectory() + "/Output/" +
DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime()) +
".mp4";
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Output");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("FolderName", "failed to create directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
mediaRecorder.setMaxDuration(30000);
mediaRecorder.setOutputFile(mediaFile);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaRecorder.start();
}
// Stop recording and remove SurfaceView
#Override
public void onDestroy() {
if (camera != null) {
camera.lock();
camera.release();
}
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
}
if (windowManager != null) {
windowManager.removeView(surfaceView);
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Please suggest any solution or error if you found.
Thanks in advance.
Here is the code which i am using to capture image, but now my question is How Do I Compress Size of Image taken by my Custom Camera
CameraSurfaceView.java:
class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
Camera camera;
CameraSurfaceView(Context context) {
super(context);
SurfaceHolder holder = this.getHolder();
holder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
camera.setDisplayOrientation(90);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Open the Camera in preview mode
this.camera = Camera.open();
this.camera.setPreviewDisplay(holder);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
}
public void takePicture(PictureCallback imageCallback) {
Camera.Parameters params = camera.getParameters();
params.setRotation(90);
camera.setParameters(params);
camera.takePicture(null, null, imageCallback);
}
}
Here is the Class which I am using to Capture Image
CameraCaptureActivity.java:
CameraSurfaceView cameraSurfaceView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_capture);
// set up our preview surface
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
cameraSurfaceView = new CameraSurfaceView(this);
preview.addView(cameraSurfaceView);
// grab out shutter button so we can reference it later
shutterButton = (Button) findViewById(R.id.btnCapture);
shutterButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
takePicture();
}
private void takePicture() {
shutterButton.setEnabled(false);
cameraSurfaceView.takePicture(this);
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO something with the image data
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
strDateFormat = simpleDateFormat.format(new Date());
String photoFile = strRecordName+strDateFormat+".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(CameraCaptureActivity.this, "Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
// Restart the preview and re-enable the shutter button so that we can take another picture
camera.stopPreview();
shutterButton.setEnabled(false);
} catch (Exception error) {
Toast.makeText(CameraCaptureActivity.this, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "CustomCamera");
}
public void onResume()
{
super.onResume();
shutterButton.setEnabled(true);
}
Do like
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap pic = BitmapFactory.decodeByteArray(data, 0, data.length);
//Rotate the image by 90 degrees before we save it
Matrix matrix = new Matrix();
matrix.postRotate(90);
pic = Bitmap.createBitmap(pic , 0, 0, pic.getWidth(), pic.getHeight(), matrix, true);
........
FileOutputStream fos = new FileOutputStream(pictureFile);
pic.compress(Bitmap.CompressFormat.PNG, 90, fOut);
}
I am making my own camera in android, then whenever I capture images the images orientation is okay. but when i open it in my external sdcard file it is like that:
this is my code:
public class CameraApp extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "IMG_";
private static final String IMAGE_FOLDER = "/PhoneController/";
private static final String EXTENTION = ".jpg";
private String pictureName = "";
public String picNameToshare = "";
static final int FOTO_MODE = 0;
String speed;
String imageFilePath;
private Handler mHandler = new Handler();
public static String imageFilePath1;
FileOutputStream fos = null;
public Bitmap framebmpScaled;
public Bitmap SelecedFrmae;
public static Bitmap mergeBitmap;
public static Bitmap bmpfULL;
Camera camera;
Button button;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.camera);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
Handler myHandler = new Handler();
if (previewing) {
camera.stopPreview();
previewing = false;
Log.e("", "one");
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
myHandler.postDelayed(mMyRunnable, 2000); // called after 5
// seconds
button.setText("Waiting...");
Log.e("", "two");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Handler myHandler = new Handler();
* myHandler.postDelayed(mMyRunnable, 5000); // called after 5
* seconds button.setText("Waiting...");
*/
}
};
private Runnable mMyRunnable = new Runnable() {
public void run() {
Camera.Parameters params = camera.getParameters();
params.set("rotation", 90);
camera.setParameters(params);
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
storePicture(mergeBitmap);
button.setText("Capture");
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Display display = getWindowManager().getDefaultDisplay();
final int ScreenWidth = display.getWidth();
final int ScreenHeight = display.getHeight();
Log.e("" + display.getWidth(), "" + display.getWidth());
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
arg0.length);
Bitmap bmpScaled1 = Bitmap.createScaledBitmap(bitmapPicture,
ScreenWidth, ScreenHeight, true);
mergeBitmap = bmpScaled1;
showPicture();
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
camera.setDisplayOrientation(90);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
void storePicture(Bitmap bm) {
mHandler.post(new Runnable() {
public void run() {
// showPicture();
}
});
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
this.pictureName = TAG + timeStamp;
picNameToshare = this.pictureName;
this.imageFilePath = IMAGE_FOLDER + this.pictureName + EXTENTION;
this.imageFilePath = sanitizePath(this.imageFilePath);
try {
checkSDCard(this.imageFilePath);
fos = new FileOutputStream(this.imageFilePath);
if (fos != null) {
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
fos.close();
}
} catch (IOException ioe) {
Log.e(TAG, "CapturePicture : " + ioe.toString());
} catch (Exception e) {
Log.e(TAG, "CapturePicture : " + e.toString());
}
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
imageFilePath1 = this.imageFilePath;
}
/**
* Check the SDCard is mounted on device
*
* #param path
* of image file
* #throws IOException
*/
void checkSDCard(String path) throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Toast.makeText(this,
"Please insert sdcard other wise image won't stored",
Toast.LENGTH_SHORT).show();
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording is exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
please help me.
Try using this
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
public class AndroidCamera extends Activity implements OnTouchListener, SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;;
PictureCallback rawCallback;
ShutterCallback shutterCallback;
PictureCallback jpegCallback;
EditText txtData, Info,Age;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
Button buttonCapturePreview = (Button) findViewById(R.id.capturepreview);
txtData = (EditText) findViewById(R.id.editText1);
Info = (EditText) findViewById(R.id.Name);
Info.setHint("enter name");
Age = (EditText) findViewById(R.id.Age);
Age.setHint("Age");
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
// onTouchEvent(null);
jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Asw");
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
};
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
{
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v)
{
if(!previewing)
{
camera = Camera.open(0);
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
}
catch (IOException e)
{
e.printStackTrace();
}
}else txtData.setText("null");
}
}});
buttonCapturePreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
captureImage();
}
private void captureImage()
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
if(camera != null && previewing)
{
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}});
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_camera, menu);
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
return super.onTouchEvent(event);
//return false;
}
I have used a button to capture the image. Now i wanted to capture and save the image with just a touch on surface view. I wrote some code.Its not showing any error but it is not working also. Could you please tell me where i am going wrong. Please help
Try this to take screen shot programmatically...
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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);
}
}
I am able to place a overlay over a live camera feed, but I also need to save the image captured by camera with that overlay.
Here is the code of my MainActivity.class file :
public class MainActivity extends Activity {
private Button takePhoto, pickPhoto;
private FrameLayout preview;
private CameraSurfaceView cameraSurfaceView;
private static final int SELECT_PICTURE_ACTIVITY_RESULT_CODE = 1;
private static final int CAMERA_PIC_REQUEST = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto = (Button) findViewById(R.id.btn_takephoto);
pickPhoto = (Button) findViewById(R.id.btn_pickPhoto);
preview = (FrameLayout) findViewById(R.id.frameLayout1);
takePhoto.setOnClickListener(clickListener);
pickPhoto.setOnClickListener(clickListener);
cameraSurfaceView = new CameraSurfaceView(MainActivity.this);
preview.addView(cameraSurfaceView);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.equals(takePhoto)) {
Camera camera = cameraSurfaceView.getCamera();
camera.takePicture(null, null, new HandlePictureStorage());
} else if (v.equals(pickPhoto)) {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*"); // to pick only images
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(photoPickerIntent,
SELECT_PICTURE_ACTIVITY_RESULT_CODE);
}
}
};
private class HandlePictureStorage implements PictureCallback {
#Override
public void onPictureTaken(byte[] picture, Camera camera) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "CameraTest" + date + ".jpg";
String filename = Environment.getExternalStorageDirectory()
+ File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(picture);
fos.close();
Toast.makeText(getApplicationContext(),
"New Image saved:" + photoFile, Toast.LENGTH_LONG)
.show();
} catch (Exception error) {
Log.d("Error",
"File" + filename + "not saved: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Image could not be saved.", Toast.LENGTH_LONG).show();
}
Intent newInt = new Intent(MainActivity.this, AddImageOverlay.class);
newInt.putExtra(Constant.BitmatpByteArray, filename);
startActivity(newInt);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_PICTURE_ACTIVITY_RESULT_CODE:
Uri selectedImageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), selectedImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Photo Picked",
Toast.LENGTH_SHORT).show();
// deal with it
break;
default:
// deal with it
break;
}
}
}
}
And the code of CameraSurfaceView.java :
public class CameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
public CameraSurfaceView(Context context) {
super(context);
// Initiate the Surface Holder properly
this.holder = this.getHolder();
this.holder.addCallback(this);
this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder h, int format, int width,
int height) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(width, height);
camera.setParameters(parameters);
camera.startPreview();
h.getSurface().setLayer(R.drawable.ic_launcher);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Open the Camera in preview mode
this.camera = Camera.open();
this.camera.setPreviewDisplay(this.holder);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when replaced with a new screen
// Always make sure to release the Camera instance
camera.stopPreview();
camera.release();
camera = null;
}
public Camera getCamera() {
return this.camera;
}
}