Picture distorted with Camera and getOptimalPreviewSize

前端 未结 2 1308
不思量自难忘°
不思量自难忘° 2020-12-03 05:36

I am on a Camera App which taking basic pictures. I have an issue when I get the best optimal preview size.

In fact, with this first code :

public vo         


        
相关标签:
2条回答
  • 2020-12-03 06:21

    The best way is to get preview size with the closest aspect ratio:

    Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
            Camera.Size result=null;
            float dr = Float.MAX_VALUE;
            float ratio = (float)width/(float)height;
    
            for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
                float r = (float)size.width/(float)size.height;
                if( Math.abs(r - ratio) < dr && size.width <= width && size.height <= height ) {
                    dr = Math.abs(r - ratio);
                    result = size;
                }
            }
    
            return result;
        }
    

    Where width and height parameters are your surface size.

    0 讨论(0)
  • 2020-12-03 06:27

    I just suffered through the same problem, and came up with a similar but lighter weight solution. I don't see anything wrong with your saving method though.

    private Camera.Size getBestPreviewSize(int width, int height)
    {
            Camera.Size result=null;    
            Camera.Parameters p = camera.getParameters();
            for (Camera.Size size : p.getSupportedPreviewSizes()) {
                if (size.width<=width && size.height<=height) {
                    if (result==null) {
                        result=size;
                    } else {
                        int resultArea=result.width*result.height;
                        int newArea=size.width*size.height;
    
                        if (newArea>resultArea) {
                            result=size;
                        }
                    }
                }
            }
        return result;
    
    }
    
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        //This line helped me set the preview Display Orientation to Portrait
                //Only works API Level 8 and higher unfortunately.
    
        camera.setDisplayOrientation(90);
    
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = getBestPreviewSize(width, height);
        parameters.setPreviewSize(size.width, size.height);
        camera.setParameters(parameters);
        camera.startPreview();
    
    }
    
    0 讨论(0)
提交回复
热议问题