How to capture an image as shown in the camera preview without chopping up its length and width

I am making a camera app for android. In it, I wanted to take a picture from the front camera to save it and show it to the user. But here I ran into some problem. Some devices work very well, but others don't work well because they shrink the image from above. I asked another question here but didn't find a good answer

I am struggling with three things and that is the optimal camera solution, the screen size (width and height), and the width and height of the bitmap captured by the camera. My app works on other devices but not on Lg because its resolution is too high.

I get the optimal resolution of the front camera as 1776 * 1080 and where, how do I get the screen dimensions as 1440 * 2392, but the image captured by the camera is 1280 * 960 wide and high. Now the problem persists here. I don't know how to get the same image as in the camera preview. I don't want any of its corners to be chopped off. So how to do it. Below is my code for getting the optimal camera.

  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 this is how I get 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 to configure 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 in the camera preview? Please help me

**

+3


source to share


1 answer


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>

      

0


source







All Articles