3

I am making an android custom camera app. In it I wanted to take a picture from front camera save it and show it to user. But I am facing some problem here. Some devices are working very perfectly but other are not working good in fact they are chopping the image in length from top. I have asked another question here but found no good answer

I am fighting with three things and that is optimal resoultion of camera, screen size (width and height) and the width and height of bitmap taken by the camera. My app is working good on other devices but not on Lg set as its resolution is too high.

I am getting the optimal resolution of front camera as 1776*1080 and where as I am getting the screen sizes as 1440 * 2392 but the picture that is taken by the camera has 1280 * 960 in width and height. Now the problem persist here. I do not know that how to get the same image as shown by the camera preview I do not want any of its corner to get chopped off. So How to do this. Following is my code for getting the optimalcamera suize....

  public static 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;
}

and here is how I am getting the screen width and height

 DisplayMetrics displaymetrics = new DisplayMetrics();
       activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int screenHeight = displaymetrics.heightPixels;
        int screenWidth = displaymetrics.widthPixels;

and below is the way I am setting the parameters :

    Camera.Size previewSize = getOptimalPreviewSize(previewSizes,screenWidth,screenHeight);
 parameters.setPreviewSize(previewSize.width,previewSize.height);
parameters.setZoom(Camera.Parameters.FOCUS_DISTANCE_OPTIMAL_INDEX);

            camera.setParameters(parameters);

**

So How can I get the full picture as shown by the camera preview. ? Please help me

**

Community
  • 1
  • 1
stacy queen
  • 280
  • 1
  • 4
  • 19
  • 1
    If you want to get the same image as shown by the camera preview, you need `setPictureSize()` for your camera. Firstly, loop on `getSupportedPictureSizes()`, and then find the closest to your preview size (with same aspect ratio). – Duy Pham Mar 19 '17 at 00:43
  • did you got solution for this? having same issue here. – Uma Achanta Aug 22 '17 at 07:00
  • @DuyPham can you explain with some code? – Uma Achanta Aug 22 '17 at 07:01

1 Answers1

0

CameraView.class

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;

public class CameraView extends Activity implements SurfaceHolder.Callback,OnClickListener {
    OutputStream output;
    File dir;
    private static final String TAG="CameraTest";
    Camera camera;
    boolean mPreviewRunning=false;
    public void onCreate(Bundle icicle){

        super.onCreate(icicle);
        Log.e(TAG,"onCreate");
        File filepath=Environment.getExternalStorageDirectory();
        dir=new File(filepath.getAbsolutePath()+"/Cam/");
        dir.mkdirs();
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.cameraview);
        mSurfaceView=(SurfaceView)findViewById(R.id.surface_camera);
        //mSurfaceView.setOnClickListener(this);

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                camera.takePicture(null,mPictureCallback,mPictureCallback);
            }
        },6000);

        mSurfaceHolder=mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
    super.onRestoreInstanceState(savedInstanceState);
}
    Camera.PictureCallback mPictureCallback=new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub
            if(data!=null)
            {
                camera.stopPreview();
                mPreviewRunning=false;
                camera.release();
                try
                {
                    BitmapFactory.Options opts=new BitmapFactory.Options();
                    Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length,opts);
                    bitmap=Bitmap.createScaledBitmap(bitmap,480,480,false);
                    File file=new File(dir,"raj.jpg");
                    try
                    {
                        output=new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
                        output.flush();
                        output.close();
                        String url=Images.Media.insertImage(getContentResolver(),bitmap, "raj.jpg",null);
                    }
                    catch(Exception e)
                    {

                    }

                    ImgCap.image.setImageBitmap(bitmap);
                }
                catch (Exception e) {
                    // TODO: handle exception
                e.printStackTrace();
                }
                setResult(585);
                finish();           }

        }
    };




protected void onResume()
{
    Log.e(TAG,"onResume");
    super.onResume();
}
protected void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
}
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        Log.e(TAG,"surfaceChanged");
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD)
        {
        Camera.CameraInfo info=new Camera.CameraInfo();
        for(int i=0;i<Camera.getNumberOfCameras();i++)
        {
            Camera.getCameraInfo(i,info);
            if(info.facing==Camera.CameraInfo.CAMERA_FACING_FRONT)
            {
                camera=Camera.open(i);
            }
        }
        }
        if(camera==null)
        {
        camera=Camera.open();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
        if(mPreviewRunning)
        {
            camera.stopPreview();
        }
        Camera.Parameters p=camera.getParameters();
        p.setPreviewSize(width, height);
        camera.setParameters(p);
        try
        {
            camera.setPreviewDisplay(holder);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        camera.startPreview();
        mPreviewRunning=true;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        Log.e(TAG,"surfaceDestroyed");
    }

    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

ImgCap.class

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class ImgCap extends Activity {
    public static ImageView image;
    private Button btn_camera;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        image = (ImageView) findViewById(R.id.image);
        btn_camera = (Button) findViewById(R.id.btn_camera);
        btn_camera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(ImgCap.this, CameraView.class);
                startActivityForResult(i, 999);

            }
});
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        if (requestCode == 999) {
            if (resultCode == 585) {

            } else {
                alert("Picture not Captured");
            }
        }
    }

    private void alert(String string) {
        // TODO Auto-generated method stub
        AlertDialog.Builder alert = new AlertDialog.Builder(ImgCap.this);
        alert.setMessage(string);
        alert.setTitle("Alert");
        alert.setNeutralButton("OK", null);
        alert.show();

    }

}

cameraview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<SurfaceView  android:id="@+id/surface_camera"
    android:layout_width="fill_parent"
    android:layout_height="10dip"
    android:layout_weight="1"
    />    

</LinearLayout>
ArulKumar
  • 35
  • 9