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" />
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)
I am creating the Android app with the camera functionality.
The camera screen contains the toolbar on the top, the surfaceview (camera preview) below the toolbar, and the camera control buttons on the bottom of the screen. The screen is always in portrait.
[Some lines of the code do not related to the issue are deleted]
This is my fragment FragmentCamera
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.dmc.R;
import com.dmc.entities.Preview;
public class CameraFragment implements View.OnClickListener, View.OnTouchListener {
public static final String ARG_CAMERA_MODE = "camera.mode";
public static final String TYPE_CAMERA_MODE_IMAGE = "image";
public static final String TYPE_CAMERA_MODE_VIDEO = "video";
public MediaRecorder mrec = new MediaRecorder();
private Camera camera;
private String mCameraMode = TYPE_CAMERA_MODE_IMAGE; //or video
private com.dmc.entities.Preview preview;
private ImageView btnStopRecording;
private SurfaceView surfaceView;
private View view;
public static FrCamera getInstance(String cameraMode) {
CameraFragment fragment = new CameraFragment();
Bundle bundle = new Bundle(1);
bundle.putString(ARG_CAMERA_MODE, cameraMode);
return fragment.setArguments(bundle);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCameraMode = getArguments().getString(ARG_CAMERA_MODE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_camera, container, false);
view.setOnTouchListener(this);
btnStopRecording = (ImageView) view.findViewById(R.id.btnStopRecording);
if (!mCameraMode.equals(TYPE_CAMERA_MODE_IMAGE)) {
btnStopRecording.setOnClickListener(this);
}
surfaceView = (SurfaceView) view.findViewById(R.id.surfaceView);
view.findViewById(R.id.imgCameraTakePicture).setOnClickListener(this);
preview = new Preview(getActivity(), (SurfaceView) view.findViewById(R.id.surfaceView));
preview.setKeepScreenOn(true);
return view;
}
#Override
public void onStart() {
super.onStart();
int numCams = Camera.getNumberOfCameras();
if (numCams > 0) {
try {
camera = Camera.open(0);
preview.setCamera(camera);
camera.startPreview();
} catch (RuntimeException ex) {
}
}
}
#Override
public void onPause() {
if (camera != null) {
camera.stopPreview();
preview.setCamera(null);
camera.release();
camera = null;
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
camera.startPreview();
}
private void startVideoRecording() {
try {
mrec = new MediaRecorder();
mrec.setCamera(camera);
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
mrec.setProfile(profile);
camera.lock();
camera.unlock();
mrec.setPreviewDisplay(preview.mHolder.getSurface());
mrec.setOutputFile(outVideoFile.getPath());
mrec.setOrientationHint(Preview.rotate);
mrec.prepare();
mrec.start();
} catch (Exception ex) {
Log.e(getClass().getName(), ex.getMessage());
}
}
protected void stopRecording() {
if (mrec != null) {
mrec.stop();
mrec.release();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgCameraTakenPicture:
// Save image
break;
case R.id.btnStopRecording:
stopRecording();
break;
case R.id.imgCameraTakePicture:
if (mCameraMode.equals(TYPE_CAMERA_MODE_IMAGE)) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
} else
startVideoRecording();
break;
}
}
}
This is the Preview
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import java.io.IOException;
import java.util.List;
public class Preview extends ViewGroup implements SurfaceHolder.Callback {
public static final float RATIO = 0.75f;
public static int rotate;
public SurfaceView mSurfaceView;
public SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
public Preview(Context context, SurfaceView sv) {
super(context);
mSurfaceView = sv;
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_CONTINUOUS_PICTURE)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
params.setJpegThumbnailQuality(100);
params.setJpegQuality(100);
// Configure image format. RGB_565 is the most common format.
List<Integer> formats = params.getSupportedPictureFormats();
if (formats.contains(PixelFormat.RGB_565))
params.setPictureFormat(PixelFormat.RGB_565);
else if (formats.contains(PixelFormat.JPEG))
params.setPictureFormat(PixelFormat.JPEG);
else params.setPictureFormat(formats.get(0));
Camera.CameraInfo camInfo = new Camera.CameraInfo();
Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);
int cameraRotationOffset = camInfo.orientation;
Camera.Parameters parameters = mCamera.getParameters();
int rotation = ((Activity) getContext()).getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break; // Natural orientation
case Surface.ROTATION_90:
degrees = 90;
break; // Landscape left
case Surface.ROTATION_180:
degrees = 180;
break;// Upside down
case Surface.ROTATION_270:
degrees = 270;
break;// Landscape right
}
int displayRotation;
if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
displayRotation = (cameraRotationOffset + degrees) % 360;
//displayRotation = (360 - displayRotation) % 360; // compensate the mirror
} else { // back-facing
displayRotation = (cameraRotationOffset - degrees + 360) % 360;
}
mCamera.setDisplayOrientation(displayRotation);
if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
rotate = (360 + cameraRotationOffset + degrees) % 360;
} else {
rotate = (360 + cameraRotationOffset - degrees) % 360;
}
parameters.set("orientation", "portrait");
parameters.setRotation(rotate);
mCamera.setParameters(params);
}
}
#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) {
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
} catch (IOException exception) {}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mHolder.getSurface() == null) {
return;
}
stopPreview();
setCamera(mCamera);
startPreview();
mCamera.startPreview();
}
public void startPreview() {
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
}
} catch (Exception e) {}
}
public void stopPreview() {
try {
if (mCamera != null)
mCamera.stopPreview();
} catch (Exception e) {}
}
}
The expected result is on the image on left side. The obtained result is on the image on the right side. The camera preview is stretched. How to fix the right aspect ratio of the camera preview?
Source code for Camera1 and Android 4-5:
#Override
protected void onResume() {
super.onResume();
camera = Camera.open(CAMERA_ID);
setPreviewSize();
}
#Override
protected void onPause() {
super.onPause();
if (camera != null)
camera.release();
camera = null;
}
...
void setPreviewSize() {
// получаем размеры экрана
Display display = getWindowManager().getDefaultDisplay();
int w1 = display.getWidth();
int h1 = display.getHeight();
boolean widthIsMax = display.getWidth() > display.getHeight();
// определяем размеры превью камеры
Camera.Size size = camera.getParameters().getPreviewSize();
RectF rectDisplay = new RectF();
RectF rectPreview = new RectF();
// RectF экрана, соотвествует размерам экрана
rectDisplay.set(0, 0, w1, h1);
// подготовка матрицы преобразования
Matrix matrix = new Matrix();
// RectF первью
if (widthIsMax) {
// превью в горизонтальной ориентации
rectPreview.set(0, 0, size.width, size.height);
// если экран будет "втиснут" в превью (третий вариант из урока)
matrix.setRectToRect(rectPreview, rectDisplay,
Matrix.ScaleToFit.START);
} else {
// превью в вертикальной ориентации
rectPreview.set(0, 0, size.height, size.width);
// если превью будет "втиснут" в экран (второй вариант из урока)
matrix.setRectToRect(rectPreview, rectDisplay,
Matrix.ScaleToFit.START);
}
// преобразование
matrix.mapRect(rectPreview);
// установка размеров surface из получившегося преобразования
h0 = (int) (rectPreview.bottom);
w0 = (int) (rectPreview.right);
surfaceView.getLayoutParams().height = h0;
surfaceView.getLayoutParams().width = w0;
}
See http://startandroid.ru/ru/uroki/vse-uroki-spiskom/264-urok-132-kamera-vyvod-izobrazhenija-na-ekran-obrabotka-povorota.html
Below is the solution of Camera Preview Stretched
It's worked on making my custom camera activity
I set the framelayout which holds the surface view that displays the camera's parameters.
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private Context mContext;
private SurfaceHolder mHolder;
private Camera mCamera;
private List<Camera.Size> mSupportedPreviewSizes;
private Camera.Size mPreviewSize;
public CameraPreview(Context context, Camera camera) {
super(context);
mContext = context;
mCamera = camera;
// supported preview sizes
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
for(Camera.Size str: mSupportedPreviewSizes)
Log.e(TAG, str.width + "/" + str.height);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// empty. surfaceChanged will take care of stuff
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.e(TAG, "surfaceChanged => w=" + w + ", h=" + h);
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or reformatting changes here
// start preview with new settings
try {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
if (mPreviewSize!=null) {
float ratio;
if(mPreviewSize.height >= mPreviewSize.width)
ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
else
ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;
// One of these methods should be used, second method squishes preview slightly
setMeasuredDimension(width, (int) (width * ratio));
// setMeasuredDimension((int) (width * ratio), height);
}
}
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.height / size.width;
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;
}
}
Reference link:
Android Camera Preview Stretched
I'm trying to build a custom camera for my application and I'm done with that, but the problem is when I'm storing the captured image, it gets rotated by 90 degrees to the left.
Following is my code, please tell me where am I getting wrong??
CamTestActivity class
public class CamTestActivity extends Activity {
private static final String TAG = "CamTestActivity";
public static final int REQUEST_CODE_GALLERY = 0x1;
private File mFileTemp;
Preview preview;
Button buttonClick, buttonGallery;
Camera camera;
Activity act;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
act = this;
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/**
* Get internal storage directory path for image save
*/
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {// if
mFileTemp = new File(Environment.getExternalStorageDirectory(), "temp_photo.png");
} else {
mFileTemp = new File(this.getFilesDir(), "temp_photo.png");
}// End of if
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);
buttonGallery = (Button) findViewById(R.id.btnGallery);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
Toast.makeText(ctx, ""+mFileTemp, Toast.LENGTH_LONG).show();
}
});
buttonClick.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
camera.autoFocus(new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
Toast.makeText(ctx, ""+mFileTemp, Toast.LENGTH_LONG).show();
}
});
return true;
}
});
buttonGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/**
* To select an image from existing files, use Intent.createChooser to open image chooser. Android will automatically display a list of supported applications, such as image gallery or file manager.
*/
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
// pick image from gallery
case REQUEST_CODE_GALLERY:
try {
InputStream inputStream = this.getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
Toast.makeText(ctx, ""+mFileTemp, Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}// End of onactivityresult
/**
* Function copyStream()-copy InputStream
*
* #param input
* #param output
* #throws IOException
* #return null
*/
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}// End of copyStream method
#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) {
try {
mFileTemp = new SaveImageTask().execute(data).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
resetCam();
Log.d(TAG, "onPictureTaken - jpeg");
}
};
private class SaveImageTask extends AsyncTask<byte[], Void, File> {
#Override
protected File doInBackground(byte[]... data) {
FileOutputStream outStream = null;
File outFile = 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());
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 outFile;
}
}
}
Preview class,
class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
Context mContext;
Preview(Context context, SurfaceView sv) {
super(context);
mContext = 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);
mCamera.startPreview();
}
} 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 width, int height) {
if(mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
// parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if(display.getRotation() == Surface.ROTATION_0)
{
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setDisplayOrientation(90);
}
if(display.getRotation() == Surface.ROTATION_90)
{
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
}
if(display.getRotation() == Surface.ROTATION_180)
{
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
}
if(display.getRotation() == Surface.ROTATION_270)
{
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setDisplayOrientation(180);
}
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
}
This is not your fault. Different devices have different default camera angle. If you want to turn your picture:
String path = *your_image_path*;
Bitmap scaledBitmap = null;
ExifInterface ei = new ExifInterface(path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),ScalingLogic.FIT, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),ScalingLogic.FIT, 180);
etc.
I solved a similar problem using the Camera rotation value:
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info);
int cameraRotation = info.orientation;
The image should be rotated of the same angle.
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>
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.