Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Camera Preview on a square screen stretched

I'm building an app for Android but The device do have a square screen. The screen is 320x320 and the camera app use the SurfaceView to show the preview as below :

    mCameraView = (SurfaceView) findViewById(R.id.surface);
    LayoutParams params = mCameraView.getLayoutParams();
    int camera_dimension = getResources().getInteger(R.integer.camera_dimension);
    params.height = camera_dimension; //320px
    params.width = camera_dimension;

    mCameraView.setLayoutParams(params);
    mCameraViewHolder = mCameraView.getHolder();
    mCameraViewHolder.addCallback(this);
    mCameraViewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

On Surface changed, I'm doing this and it works but the supporter preview is w480 x h320

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

    int mWidth = w;
    int mHeight = h;
    int mFormat = format;

    try {
        mCameraAccess.mCamera.stopPreview();
    } catch (Exception e){
        // ignore: tried to stop a non-existent preview
    }
    Camera.Parameters param = mCameraAccess.mCamera.getParameters();

    List<Camera.Size> SupportedPreview = param.getSupportedPreviewSizes();
    int ScreenSize = getResources().getInteger(R.integer.camera_dimension);

    for (int i = 0; i < SupportedPreview.size(); i++) {
        if (SupportedPreview.get(i).height == ScreenSize) {
            param.setPreviewSize(SupportedPreview.get(i).width, SupportedPreview.get(i).height);
            break;
        }
    }
    mCameraAccess.mCamera.setParameters(param);
    mCameraAccess.mCamera.startPreview();
}

How can make sure that my preview inside the viewholder is not compressed but a kind of centercrop. As the preview is a rectangle, I just need the square centered on the image. Usually I'm using scaleType but it's not supported in Surface view

Any idea ?

like image 475
Seb Avatar asked Dec 09 '15 10:12

Seb


1 Answers

The solution which i have figured out is:

1)-Keep surface view full screen,so that is doesn't stretch.

2)-Put a view over surfaceview with full opacity.So that is looks like camera is already squared.

3)-After capturing image or video,you will have to crop them.

For video you have to use some video processing library like javacv.Using this library you can extract video frames,convert them to bitmap,crop bitmap in square and then re-encode into video.

To get accurate results you will need to play around with different techniques like zooming camera during capture etc. according to your needs.

Original Image:

enter image description here

Squared Image:

enter image description here

like image 82
Muhammad Umair Shafique Avatar answered Sep 27 '22 16:09

Muhammad Umair Shafique