从自定义相机捕获图像

时间:2016-10-10 10:54:55

标签: android camera

我正在创建一个自定义相机,当我点击拍摄照片时,我遇到了一些错误。

我使用了SurfaceView拍摄照片。

错误:

10-10 16:17:00.269: E/AndroidRuntime(29256): FATAL EXCEPTION: main
10-10 16:17:00.269: E/AndroidRuntime(29256): Process: com.example.abc, PID: 29256
10-10 16:17:00.269: E/AndroidRuntime(29256): java.lang.RuntimeException: startPreview failed
10-10 16:17:00.269: E/AndroidRuntime(29256):    at android.hardware.Camera.startPreview(Native Method)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at com.example.abc.Custom_CameraActivity.onClick(Custom_CameraActivity.java:237)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at android.view.View.performClick(View.java:4471)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at android.view.View$PerformClick.run(View.java:18778)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at android.os.Handler.handleCallback(Handler.java:808)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at android.os.Handler.dispatchMessage(Handler.java:103)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at android.os.Looper.loop(Looper.java:193)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at android.app.ActivityThread.main(ActivityThread.java:5304)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at java.lang.reflect.Method.invokeNative(Native Method)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at java.lang.reflect.Method.invoke(Method.java:515)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
10-10 16:17:00.269: E/AndroidRuntime(29256):    at dalvik.system.NativeStart.main(Native Method)

我的代码:

public class Custom_CameraActivity extends Activity implements OnClickListener, Callback {
private static Camera camera;
private static int vesion;
private static int which;
private int brightness;
private Bitmap cameraBitmap;
private ImageView capt_btn;
int currBrightness;
private ImageView flash_btn;
private VerticalSeekBar greenSeekbar;
@SuppressLint({"HandlerLeak"})
Handler handler;
private boolean hasFlash;
private boolean isLighOn;
private ImageView list_btn;
private PictureCallback mPicture;
private int max_zoom_factor;
private boolean previewing;
private int screenHeight;
private int screenWidth;
private Bitmap surfaceBitmap;
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
private ImageView turn_btn;
private SeekBar zoomSeekBar;
private int zoom_factor;

public Custom_CameraActivity() {
    this.previewing = false;
    this.isLighOn = false;
    this.zoom_factor = 0;
    this.max_zoom_factor = 0;

    this.handler = new Handler(){

        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Toast.makeText(Custom_CameraActivity.this, Custom_CameraActivity.this.getResources().getString(R.string.txt_toastPhotoNotSaved), 0).show();
            } else {
                Toast.makeText(Custom_CameraActivity.this, Custom_CameraActivity.this.getResources().getString(R.string.txt_toastPhotoSaved), 0).show();
            }
            Custom_CameraActivity.this.surfaceView.setBackgroundColor(Color.argb(100, 0, MotionEventCompat.ACTION_MASK, 0));
        }
    };

    this.mPicture = new PictureCallback() {

        @Override

        public void onPictureTaken(byte[] data, Camera camera) {
            Custom_CameraActivity.this.cameraBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            Custom_CameraActivity.this.cameraBitmap = Custom_CameraActivity.getResizedBitmap(Custom_CameraActivity.this.cameraBitmap, Custom_CameraActivity.this.screenHeight, Custom_CameraActivity.this.screenWidth);
            Custom_CameraActivity.this.joinBitmap();
            camera.startPreview();
        }
    };
}

static {
    camera = null;
    which = 0;
    vesion = 0;
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Window window = getWindow();
    requestWindowFeature(1);
    window.setFlags(AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT);
    setContentView(R.layout.activity_main);
    bindView();
    init();
    addListener();
}

protected void onResume() {
    super.onResume();
}

private void bindView() {
    this.surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
    this.flash_btn = (ImageView) findViewById(R.id.flash);
    this.capt_btn = (ImageView) findViewById(R.id.capture);
    this.turn_btn = (ImageView) findViewById(R.id.turn);
    this.zoomSeekBar = (SeekBar) findViewById(R.id.zoom_seekbar);
    this.greenSeekbar = (VerticalSeekBar) findViewById(R.id.sbGreen);
    this.list_btn = (ImageView) findViewById(R.id.list);
}

private void init() {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    this.screenHeight = metrics.heightPixels;
    this.screenWidth = metrics.widthPixels;
    this.surfaceHolder = this.surfaceView.getHolder();
    this.surfaceHolder.addCallback(this);
    this.surfaceHolder.setType(3);
    try {
        this.brightness = System.getInt(getContentResolver(), "screen_brightness");
        this.currBrightness = this.brightness;
    } catch (Exception e) {
        Log.m0d("TAG", "Cannot access system brightness");
        e.printStackTrace();
    }
    this.greenSeekbar.setMax(220);
    this.greenSeekbar.setProgress(100);
    this.surfaceView.setBackgroundColor(Color.argb(100, 0, MotionEventCompat.ACTION_MASK, 0));
}

private void addListener() {

    this.flash_btn.setOnClickListener(this);

    this.capt_btn.setOnClickListener(this);

    this.turn_btn.setOnClickListener(this);

    this.list_btn.setOnClickListener(this);

    this.zoomSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub
            Custom_CameraActivity.this.zoomTo(progress, false);
        }
    });

    this.greenSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub
            Custom_CameraActivity.this.surfaceView.setBackgroundColor(Color.argb(progress, 0, MotionEventCompat.ACTION_MASK, 0));
        }
    });
}

private void screenBrightness(double newBrightnessValue) {
    LayoutParams lp = getWindow().getAttributes();
    lp.screenBrightness = ((float) newBrightnessValue) / 255.0f;
    getWindow().setAttributes(lp);
}

@SuppressWarnings("deprecation")
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.turn:
            turn();
        case R.id.capture:
            camera.takePicture(null, null, this.mPicture);
        case R.id.flash:
            this.hasFlash = getApplicationContext().getPackageManager().hasSystemFeature("android.hardware.camera.flash");
            if (this.hasFlash) {
                Parameters p = camera.getParameters();
                if (this.isLighOn) {
                    p.setFlashMode("off");
                    camera.setParameters(p);
                    flash_btn.setBackgroundResource(R.drawable.ic_off);
                    camera.stopPreview();
                    camera.startPreview();
                    this.isLighOn = false;
                    return;
                }
                p.setFlashMode("torch");
                camera.setParameters(p);
                flash_btn.setBackgroundResource(R.drawable.ic_on);
                camera.startPreview();
                this.isLighOn = true;
                return;
            }
            AlertDialog alert = new AlertDialog.Builder(this).create();
            alert.setTitle(getResources().getString(R.string.txt_dialogFlashTitle));
            alert.setMessage(getResources().getString(R.string.txt_dialogFlashMsg));

            alert.setButton(getResources().getString(R.string.txt_dialogFlashBtnOk), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            });
            alert.show();
        case R.id.list:
            startActivity(new Intent(this, MySavedPics.class));
        default:
    }
}

void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
    if (camera != null) {
        int result;
        CameraInfo info = new CameraInfo();
        int degrees = 0;
        switch (activity.getWindowManager().getDefaultDisplay().getRotation()) {
            case 0:
                degrees = 0;
                break;
            case 1:
                degrees = 90;
                break;
            case 2:
                degrees = 180;
                break;
            case 3:
                degrees = 270;
                break;
        }
        if (info.facing == 1) {
            result = (360 - ((info.orientation + degrees) % 360)) % 360;
        } else {
            result = ((info.orientation - degrees) + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }
}


public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    if (this.previewing) {
        camera.stopPreview();
        this.previewing = false;
    }
    Parameters parameters = camera.getParameters();
    if (camera != null) {
        try {
            camera.setPreviewDisplay(this.surfaceHolder);
            camera.startPreview();
            this.previewing = true;
            if (parameters.isZoomSupported()) {
                this.max_zoom_factor = parameters.getMaxZoom();
                this.zoomSeekBar.setMax(this.max_zoom_factor);
                this.zoomSeekBar.setProgress(this.zoom_factor);
                this.zoomSeekBar.setVisibility(0);
                return;
            }
            this.zoomSeekBar.setVisibility(8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void surfaceCreated(SurfaceHolder holder) {
    try {
        if (vesion == 1) {
            Camera.open(which);
        } else {
            camera = Camera.open();
        }
    } catch (Exception e) {
        camera.release();
    }
    try {
        Parameters parameters = camera.getParameters();
        if (getResources().getConfiguration().orientation != 2) {
            parameters.set("orientation", "portrait");
            camera.setDisplayOrientation(90);
            parameters.setRotation(90);
        } else {
            parameters.set("orientation", "landscape");
            camera.setDisplayOrientation(0);
            parameters.setRotation(0);
        }
        camera.setParameters(parameters);
        camera.setPreviewDisplay(this.surfaceHolder);
    } catch (IOException e2) {
        camera.release();
    }
    camera.startPreview();
}

public void surfaceDestroyed(SurfaceHolder arg0) {
    camera.stopPreview();
    camera.release();
    camera = null;
    vesion = 0;
    this.previewing = false;
}

public void zoomTo(int new_zoom_factor, boolean update_seek_bar) {
    Log.m0d("TAG", "ZoomTo(): " + new_zoom_factor);
    if (new_zoom_factor < 0) {
        new_zoom_factor = 0;
    }
    if (new_zoom_factor > this.max_zoom_factor) {
        new_zoom_factor = this.max_zoom_factor;
    }
    if (new_zoom_factor != this.zoom_factor && camera != null) {
        Parameters parameters = camera.getParameters();
        if (parameters.isZoomSupported()) {
            Log.m0d("TAG", "zoom was: " + parameters.getZoom());
            parameters.setZoom(new_zoom_factor);
            try {
                camera.setParameters(parameters);
                this.zoom_factor = new_zoom_factor;
                if (update_seek_bar) {
                    this.zoomSeekBar.setProgress(this.max_zoom_factor - this.zoom_factor);
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
    }
}

public void turn() {
    if (VERSION.SDK_INT <= 9) {
        AlertDialog.Builder ab1 = new AlertDialog.Builder(this);
        ab1.setTitle(getResources().getString(R.string.txt_dialogTurnTitlesec));
        ab1.setMessage(getResources().getString(R.string.txt_dialogTurnMsgsec));
        ab1.setCancelable(false);
        ab1.setPositiveButton(getResources().getString(R.string.txt_dialogTurnBtnOksec), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        }).show();
        //9967559972
    } else if (Camera.getNumberOfCameras() >= 2) {
        vesion = 1;
        camera.stopPreview();
        camera.release();
        switch (which) {
            case 0:
                camera = Camera.open(1);
                this.flash_btn.setEnabled(false);
                camera.setDisplayOrientation(90);
                which = 1;
                break;
            case 1:
                camera = Camera.open(0);
                this.flash_btn.setEnabled(true);
                camera.setDisplayOrientation(90);
                which = 0;
                break;
        }
        try {
            camera.setPreviewDisplay(this.surfaceHolder);
            camera.setPreviewCallback(null);
            camera.startPreview();
        } catch (IOException e) {
            camera.release();
            camera = null;
        }
    } else {
        vesion = 0;
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        ab.setTitle(getResources().getString(R.string.txt_dialogTurnTitle));
        ab.setMessage(getResources().getString(R.string.txt_dialogTurnMsg));
        ab.setCancelable(false);
        ab.setPositiveButton(getResources().getString(R.string.txt_dialogTurnBtnOk), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        }).show();
    }
}

public void joinBitmap() {
    this.surfaceView.setBackgroundColor(-16711936);
    this.surfaceView.setDrawingCacheEnabled(true);
    this.surfaceView.buildDrawingCache();
    this.surfaceView.refreshDrawableState();
    new Thread() {
        public void run() {
            try {
                Custom_CameraActivity.this.surfaceBitmap = Custom_CameraActivity.this.surfaceView.getDrawingCache();
                if (Custom_CameraActivity.this.surfaceBitmap != null) {
                    File pictureFile = Custom_CameraActivity.getOutputMediaFile();
                    if (pictureFile != null) {
                        Bitmap finalbitmap = Custom_CameraActivity.overlay(Custom_CameraActivity.this.cameraBitmap, Custom_CameraActivity.this.surfaceBitmap, Custom_CameraActivity.this.greenSeekbar.getProgress() + 15);
                        if (pictureFile.exists()) {
                            pictureFile.delete();
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(pictureFile);
                            finalbitmap.compress(CompressFormat.JPEG, 90, out);
                            out.flush();
                            out.close();
                        } catch (FileNotFoundException e) {
                        } catch (IOException e2) {
                        }
                        Custom_CameraActivity.this.handler.sendEmptyMessage(1);
                        return;
                    }
                    return;
                }
                Custom_CameraActivity.this.handler.sendEmptyMessage(0);
            } catch (Exception e3) {
            }
        }
    }.start();
}

public static Bitmap getResizedBitmap(Bitmap bitmap, int newHeight, int newWidth) {
    Bitmap dest = null;
    try {
        int sourceWidth = bitmap.getWidth();
        int sourceHeight = bitmap.getHeight();
        float scale = Math.min(((float) sourceWidth) / ((float) newWidth), ((float) sourceHeight) / ((float) newHeight));
        float scaledWidth = ((float) sourceWidth/ scale);
        float scaledHeight = ((float) sourceHeight/ scale);
        dest = Bitmap.createBitmap(Bitmap.createScaledBitmap(bitmap, (int) scaledWidth, (int) scaledHeight, true), (int) ((scaledWidth - ((float) newWidth)) / 2.0f), (int) ((scaledHeight - ((float) newHeight)) / 2.0f), newWidth, newHeight);
    } catch (Exception e) {
    }
    return dest;
}

public static Bitmap overlay(Bitmap bitmap1, Bitmap bitmapOverlay, int opacity) {
    Bitmap resultBitmap = Bitmap.createBitmap(bitmapOverlay.getWidth(), bitmapOverlay.getHeight(), Config.ARGB_8888);
    Canvas c = new Canvas(resultBitmap);
    c.drawBitmap(bitmap1, 0.0f, 0.0f, null);
    Paint p = new Paint();
    p.setAlpha(opacity);
    c.drawBitmap(bitmapOverlay, 0.0f, 0.0f, p);
    return resultBitmap;
}

@SuppressLint({"SimpleDateFormat"})
private static File getOutputMediaFile() {
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "Night Vision Camera");
    if (mediaStorageDir.exists() || mediaStorageDir.mkdirs()) {
        return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg");
    }
    Log.m0d("Night Vision Camera", "failed to create directory");
    return null;
}
}

0 个答案:

没有答案