自定义相机应用android的问题 - 旋转270,拉伸捕获视图,而不是让所有的功能 [英] Custom camera app in android problems - rotation 270, stretched capture view and not getting all functions

查看:628
本文介绍了自定义相机应用android的问题 - 旋转270,拉伸捕获视图,而不是让所有的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从$帮助C $ç https://github.com/josnidhin/Android - 相机 - 示例

但面临着一些问题,如:


  1. 如何添加自动对焦和闪光灯的功能。 - 在上次编辑code解决

  2. 的时候屏幕方向是270那么真实视图显示180度旋转。

  3. 拍摄视图呈现捉襟见肘。

code 从那里我所谓的自定义相机类

 相机Cam = Camera.open();
    如果(空== CAM)
    {
        //没有摄像头的存在
        意图I =新意图(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(ⅰ,RESULT_LOAD_IMAGE);
    }
    其他
    {
        cam.release();
        意向意图=新意图(CreateList.this,CamTestActivity.class);
        startActivityForResult(意向,TAKE_PICTURE);
    }

自定义相机类的 CamTestActivity.class

 进口java.io.FileNotFoundException;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;进口android.app.Activity;
进口android.content.Context;
进口android.content.Intent;
进口android.hardware.Camera;
进口android.hardware.Camera.AutoFocusCallback;
进口android.hardware.Camera.PictureCallback;
进口android.hardware.Camera.ShutterCallback;
进口android.os.Bundle;
进口android.os.Environment;
进口android.util.Log;
进口android.view.SurfaceView;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.view.View.OnLongClickListener;
进口android.view.ViewGroup.LayoutParams;
进口android.view.Window;
进口android.view.WindowManager;
进口android.widget.Button;
进口android.widget.FrameLayout;进口com.example.R;公共类CamTestActivity延伸活动{
    私有静态最后弦乐TAG =CamTestActivity;
    preVIEW preVIEW;
    按钮buttonClick,buttonCancel;
    摄像头摄像头;
    字符串文件名;
    活动的行为;
    上下文CTX;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        CTX =这一点;
        ACT =这一点;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        。getWindow()addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);        的setContentView(R.layout.take_picture);        preVIEW =新的preVIEW(这一点,(SurfaceView)findViewById(R.id.surfaceView));
        preview.setLayoutParams(新的LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        ((的FrameLayout)findViewById(R.id. preVIEW))addView(preVIEW)。
        preview.setKeepScreenOn(真);        buttonClick =(按钮)findViewById(R.id.buttonClick);
        buttonCancel =(按钮)findViewById(R.id.buttonCancel);        buttonClick.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                camera.takePicture(shutterCallback,rawCallback,jpegCallback);
            }
        });        buttonClick.setOnLongClickListener(新OnLongClickListener(){
            @覆盖
            公共布尔onLongClick(查看为arg0){
                camera.autoFocus(新AutoFocusCallback(){
                    @覆盖
                    公共无效onAutoFocus(布尔focus_flag,相机Cam){
                        如果(focus_flag)
                            cam.takePicture(shutterCallback,rawCallback,jpegCallback);
                    }
                });
                返回true;
            }
        });        buttonCancel.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                完();
            }
        });
    }    @覆盖
    保护无效onResume(){
        super.onResume();
        // preview.camera = Camera.open();
        相机= Camera.open(0);
        camera.start preVIEW();
        preview.setCamera(摄像头);
    }    @覆盖
    保护无效的onPause(){
        如果(相机!= NULL){
            camera.stop preVIEW();
            preview.setCamera(NULL);
            camera.release();
            摄像头= NULL;
        }
        super.onPause();
    }    私人无效resetCam(){
        camera.start preVIEW();
        preview.setCamera(摄像头);        意图I =新意图();
        i.putExtra(captured_img,文件名);
        的setResult(RESULT_OK,I);
        完();
    }    ShutterCallback shutterCallback =新ShutterCallback(){
        公共无效onShutter(){
            // Log.d(TAGonShutter'd);
        }
    };    PictureCallback rawCallback =新PictureCallback(){
        公共无效onPictureTaken(字节[]数据,相机摄像头){
            // Log.d(TAGonPictureTaken - 原始);
        }
    };    PictureCallback jpegCallback =新PictureCallback(){
        公共无效onPictureTaken(字节[]数据,相机摄像头){
            FileOutputStream中outStream = NULL;
            尝试{
                //写入SD卡
                文件名=的String.format(Environment.getExternalStorageDirectory()+/FansRave_UploadDeal_Pic.jpg);                outStream =新的FileOutputStream(文件名);
                outStream.write(数据);
                outStream.close();
                Log.d(TAGonPictureTaken - 写字节:+ data.length);                resetCam();
            }赶上(FileNotFoundException异常五){
                e.printStackTrace();
            }赶上(IOException异常五){
                e.printStackTrace();
            }
            Log.d(TAGonPictureTaken - JPEG);
        }
    };
}

preview.class

 进口java.io.IOException异常;
进口的java.util.List;进口android.content.Context;
进口android.content.pm.PackageManager;
进口android.content.res.Configuration;
进口android.hardware.Camera;
进口android.hardware.Camera.Parameters;
进口android.hardware.Camera.Size;
进口android.util.Log;
进口android.view.SurfaceHolder;
进口android.view.SurfaceView;
进口android.view.View;
进口android.view.ViewGroup;类preVIEW扩展的ViewGroup实现SurfaceHolder.Callback {
    私人最终字符串标记=preVIEW    SurfaceView mSurfaceView;
    SurfaceHolder mHolder;
    尺寸M previewSize;
    清单<尺寸和GT; mSupported previewSizes;
    相机mCamera;
    上下文mContext;    preVIEW(上下文的背景下,SurfaceView SV){
        超级(上下文);        mContext =背景;
        mSurfaceView = SV;        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(本);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }    公共无效setCamera(相机摄像机){
        mCamera =摄像头;
        如果(mCamera!= NULL){
            mSupported previewSizes = mCamera.getParameters()getSupported previewSizes()。
            requestLayout();            //获取相机参数
            Camera.Parameters PARAMS = mCamera.getParameters();            清单<串GT; focusModes = params.getSupportedFocusModes();
            如果(focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)){
                //设置对焦模式
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                //设置相机参数
                mCamera.setParameters(PARAMS);
            }
        }
    }    @覆盖
    保护无效onMeasure(INT widthMeasureSpec,诠释heightMeasureSpec){
        //我们故意忽略孩子的测量,因为充当
        //封装到中心相机preVIEW而不是SurfaceView
        //伸展它。        最终诠释宽度= resolveSize(getSuggestedMinimumWidth(),widthMeasureSpec);
        最终诠释身高= resolveSize(getSuggestedMinimumHeight(),heightMeasureSpec);
        setMeasuredDimension(宽度,高度);        如果(mSupported previewSizes!= NULL){
            米previewSize = getOptimal previewSize(mSupported previewSizes,宽,高);
        }
    }    @覆盖
    保护无效onLayout(布尔变化,诠释L,INT T,INT R,INT B){
        如果(变更&放大器;&放大器; getChildCount()大于0){
            最后查看孩子= getChildAt(0);            最终诠释宽度= R - 1;
            最终诠释身高= B - 吨;            INT previewWidth =宽度;
            INT previewHeight =高度;            如果(M previewSize!= NULL){
                previewWidth = M previewSize.width;
                previewHeight = M previewSize.height;
            }            //中心父项子SurfaceView。
            如果(宽* previewHeight>高* previewWidth){
                最终诠释scaledChildWidth = previewWidth *高/ previewHeight;
                child.layout((宽 - scaledChildWidth)/ 2,0,(宽+ scaledChildWidth)/ 2,高度);
            }其他{
                最终诠释scaledChildHeight = previewHeight *宽/ previewWidth;
                child.layout(0,(高度 - scaledChildHeight)/ 2,宽度,(高度+ scaledChildHeight)/ 2);
            }
        }
    }    公共无效surfaceCreated(SurfaceHolder持有人){
        //表面有被创建,获取摄像机,并告诉它来绘制。
        尝试{
            如果(mCamera!= NULL){
                如果(getResources()。getConfiguration()。方向== Configuration.ORIENTATION_LANDSCAPE){
                    Global.orientation =横向;
                    Log.e(定向模式,+ Global.orientation);
                }否则如果(getResources()。getConfiguration()。方向== Configuration.ORIENTATION_PORTRAIT){
                    mCamera.stop preVIEW();
                    mCamera.setDisplayOrientation(90);
                    mCamera.start preVIEW();
                    Global.orientation =纵向;
                    Log.e(定向模式,+ Global.orientation);
                }
                mCamera.set previewDisplay(支架);
            }
        }赶上(IOException异常除外){
            Log.e(TAG,IOException异常造成集previewDisplay()除外);
            mCamera.release();
            mCamera = NULL;
        }
    }    公共无效surfaceDestroyed(SurfaceHolder持有人){
        //当我们回到地面就会被破坏,因此停止preVIEW。
        如果(mCamera!= NULL){
            mCamera.stop preVIEW();
            mCamera.set previewCallback(NULL);
            mCamera.release();
            mCamera = NULL;
        }
    }    私人尺寸getOptimal previewSize(列表<尺寸和GT;的大小,INT W,INT高){
        最终双ASPECT_TOLERANCE = 0.2;
        双targetRatio =(双)W / H;
        如果(大小== NULL)返回NULL;        大小optimalSize = NULL;
        双minDiff = Double.MAX_VALUE;        INT targetHeight = H;        //尝试找到一个大小匹配纵横比和尺寸
        对于(尺寸大小:大小){
            双率=(双)size.width / size.height;
            如果(Math.abs(比 - targetRatio)GT; ASPECT_TOLERANCE)继续;
            如果(Math.abs(size.height - targetHeight)LT; minDiff){
                optimalSize =大小;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }        //找不到一个长宽比匹配,忽略此要求
        如果(optimalSize == NULL){
            minDiff = Double.MAX_VALUE;
            对于(尺寸大小:大小){
                如果(Math.abs(size.height - targetHeight)LT; minDiff){
                    optimalSize =大小;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        返回optimalSize;
    }    公共无效surfaceChanged(SurfaceHolder架,INT格式,诠释W,INT高){
        如果(mCamera!= NULL){
            Camera.Parameters参数= mCamera.getParameters();
            parameters.set previewSize(M previewSize.width,男previewSize.height);            //闪光
            如果(mContext.getPackageManager()。hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
                parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);            requestLayout();            mCamera.setParameters(参数);
            mCamera.start preVIEW();            mCamera.autoFocus(NULL);
        }
    }
}

XML文件的 take_picture.xml

 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:ID =@ + ID /布局
机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT
机器人:方向=垂直><的FrameLayout
    机器人:ID =@ + ID / preVIEW
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =0dp
    机器人:layout_weight =1>    < SurfaceView
        机器人:ID =@ + ID / surfaceView
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT/>    < RelativeLayout的
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =FILL_PARENT
        机器人:方向=垂直>        <按钮
            机器人:ID =@ + ID / buttonClick
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_centerHorizo​​ntal =真
            机器人:layout_centerVertical =真
            机器人:背景=@绘制/ button_gradient/>        <按钮
            机器人:ID =@ + ID / buttonCancel
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_alignParentBottom =真
            机器人:layout_alignParentLeft =真
            机器人:文字=取消/>
    < / RelativeLayout的>
< /&的FrameLayout GT;< / LinearLayout中>


解决方案

如果您收到定制的相机问题,那么请使用意向的摄像头,低于code使图像旋转可能

 位图BM = BitmapFactory.de codeStream(新的FileInputStream(MFILE),空,mBitmapFactoryOptions);
            位图位图= BM;            ExifInterface EXIF​​ =新ExifInterface(的ImagePath);            INT方向= exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,1);            Log.e(ExifInteface .........,旋转=+方向);            // exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90,90);            Log.e(方向,+方向);
            矩阵M =新的Matrix();            如果((取向== ExifInterface.ORIENTATION_ROTATE_180)){
                m.postRotate(180);
                // m.postScale((浮点)bm.getWidth(),(浮点)
                // bm.getHeight());
                //如果(微米。preRotate(90)){
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(BM,0,0,bm.getWidth(),bm.getHeight()中,m,真);
                返回位图;
            }否则如果(方向== ExifInterface.ORIENTATION_ROTATE_90){
                m.postRotate(90);
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(BM,0,0,bm.getWidth(),bm.getHeight()中,m,真);
                返回位图;
            }否则如果(方向== ExifInterface.ORIENTATION_ROTATE_270){
                m.postRotate(270);
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(BM,0,0,bm.getWidth(),bm.getHeight()中,m,真);
                返回位图;            }

I got the help from code https://github.com/josnidhin/Android-Camera-Example

But facing some problems like:

  1. How to add functionalities of auto focus and flash. - solved in last edited code
  2. The when screen orientation is 270 so real view shows 180 degree rotated.
  3. Capture view is showing stretched.

The CODE from where i called the custom camera class

    Camera cam = Camera.open();
    if (null == cam) 
    {
        // no camera exists
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);
    } 
    else 
    {
        cam.release();
        Intent intent = new Intent(CreateList.this, CamTestActivity.class);
        startActivityForResult(intent, TAKE_PICTURE);
    }

Custom camera class CamTestActivity.class

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
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 com.example.R;

public class CamTestActivity extends Activity {
    private static final String TAG = "CamTestActivity";
    Preview preview;
    Button buttonClick, buttonCancel;
    Camera camera;
    String fileName;
    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.take_picture);

        preview = new Preview(this, (SurfaceView) findViewById(R.id.surfaceView));
        preview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        ((FrameLayout) findViewById(R.id.preview)).addView(preview);
        preview.setKeepScreenOn(true);

        buttonClick = (Button) findViewById(R.id.buttonClick);
        buttonCancel = (Button) findViewById(R.id.buttonCancel);

        buttonClick.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                camera.takePicture(shutterCallback, rawCallback, jpegCallback);
            }
        });

        buttonClick.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View arg0) {
                camera.autoFocus(new AutoFocusCallback() {
                    @Override
                    public void onAutoFocus(boolean focus_flag, Camera cam) {
                        if (focus_flag)
                            cam.takePicture(shutterCallback, rawCallback, jpegCallback);
                    }
                });
                return true;
            }
        });

        buttonCancel.setOnClickListener(new OnClickListener() {
            public void onClick(View v)     {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // preview.camera = Camera.open();
        camera = Camera.open(0);
        camera.startPreview();
        preview.setCamera(camera);
    }

    @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);

        Intent i = new Intent();
        i.putExtra("captured_img", fileName);
        setResult(RESULT_OK, i);
        finish();
    }

    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) {
            FileOutputStream outStream = null;
            try     {
                // Write to SD Card
                fileName = String.format(Environment.getExternalStorageDirectory() + "/FansRave_UploadDeal_Pic.jpg");

                outStream = new FileOutputStream(fileName);
                outStream.write(data);
                outStream.close();
                Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);

                resetCam();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } 
            Log.d(TAG, "onPictureTaken - jpeg");
        }
    };
}

Preview.class

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
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;
    Context mContext;

    Preview(Context context, SurfaceView sv) {
        super(context);

        mContext = 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_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 center 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) {
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    Global.orientation = "LANDSCAPE";
                    Log.e("Orientation mode", "" + Global.orientation);
                } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)     {
                    mCamera.stopPreview();
                    mCamera.setDisplayOrientation(90);
                    mCamera.startPreview();
                    Global.orientation = "PORTRAIT";
                    Log.e("Orientation mode", "" + Global.orientation);
                }
                mCamera.setPreviewDisplay(holder);
            }
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
            mCamera.release();
            mCamera = null;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.2;
        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);

            // for flash
            if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
                parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);

            requestLayout();

            mCamera.setParameters(parameters);
            mCamera.startPreview();

            mCamera.autoFocus(null);
        }
    }
}

XML file take_picture.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<FrameLayout
    android:id="@+id/preview"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/buttonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:background="@drawable/button_gradient" />

        <Button
            android:id="@+id/buttonCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:text="Cancel" />
    </RelativeLayout>
</FrameLayout>

</LinearLayout>

解决方案

If you getting problem with custom camera then please use intent camera with below code so image rotation is possible

    Bitmap bm = BitmapFactory.decodeStream(new FileInputStream(mFile), null, mBitmapFactoryOptions);
            Bitmap bitmap = bm;

            ExifInterface exif = new ExifInterface(ImagePath);

            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

            Log.e("ExifInteface .........", "rotation =" + orientation);

            // exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);

            Log.e("orientation", "" + orientation);
            Matrix m = new Matrix();

            if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
                m.postRotate(180);
                // m.postScale((float) bm.getWidth(), (float)
                // bm.getHeight());
                // if(m.preRotate(90)){
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
                return bitmap;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                m.postRotate(90);
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
                return bitmap;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                m.postRotate(270);
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
                return bitmap;

            }

这篇关于自定义相机应用android的问题 - 旋转270,拉伸捕获视图,而不是让所有的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆