你如何获得一个简单的摄像头程序为Android的工作? [英] How do you get a simple camera program working for Android?

查看:99
本文介绍了你如何获得一个简单的摄像头程序为Android的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始编程的Java,我需要得到一个简单的应用起来,显示的摄像头,拍照和地方将发送图像数据。

I just started programming in Java, and I need to get a simple application up that shows the camera, takes a picture, and sends that picture data somewhere.

我一直在寻找所有网站上试图找到和预期一样好相机的教程,但显然它们都需要我没有但一些内在的知识。

I have been searching all over the web trying to find a good camera tutorial that worked as expected, but apparently they all require some inner knowledge that I do not have yet.

页面,commonsWare指出,code,它有一些样品code在它使用相机。我已PictureDemo code和得到它没有故障运行。然而,它只是带来了一个黑色的屏幕。我想这是因为程序实际上并未启动preVIEW,或在主功能的摄像头,但每次我尝试添加code我想我需要,我得到异常。

On this page, commonsWare pointed to code that had some sample code in it for using the camera. I have taken the PictureDemo code and got it running with no errors. However, it only brings up a black screen. I assume this is because the program is not actually activating the preview, or camera in the main function, but every time I try adding the code I think I need, I am getting exceptions.

所以我的问题是,我需要做什么,在主要的功能添加到拿相机去?还是有更好的教程的地方,我可以看到简单的基本code获取相机了?

So my question is, what do I need to add in the main function to get the camera going? Or is there a better tutorial somewhere that I can see simple basic code for getting the camera up?

package assist.core;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MainActivity extends Activity
{
    private SurfaceView preview = null;
    private SurfaceHolder previewHolder = null;
    private Camera camera = null;
    private boolean inPreview = false;

    /**
     * 
     */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        //Call the parent class
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        preview = (SurfaceView) findViewById(R.id.preview);
        previewHolder = preview.getHolder();
        previewHolder.addCallback(surfaceCallback);
        previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void onResume() {
        super.onResume();
        //Get the camera instance
        camera = CameraFinder.INSTANCE.open();
    }

    @Override
    public void onPause() {
        if (inPreview) {
            camera.stopPreview();
        }

        camera.release();
        camera = null;
        inPreview = false;

        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_SEARCH) {
            if (inPreview) {
                camera.takePicture(null, null, photoCallback);
                inPreview = false;
            }

            return(true);
        }

        return(super.onKeyDown(keyCode, event));
    }

    private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
        Camera.Size result = null;

        for (Camera.Size size : parameters.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);
    }

    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera.setPreviewDisplay(previewHolder);
            }
            catch (Throwable t) {
                Log.e("MainActivity-surfaceCallback", "Exception in setPreviewDisplay()", t);
                Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = getBestPreviewSize(width, height, parameters);

            if (size != null) {
                parameters.setPreviewSize(size.width, size.height);
                parameters.setPictureFormat(PixelFormat.JPEG);

                camera.setParameters(parameters);
                camera.startPreview();
                inPreview = true;
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // no-op
        }
    };

    Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            new SavePhotoTask().execute(data);
            camera.startPreview();
            inPreview = true;
        }
    };

    class SavePhotoTask extends AsyncTask<byte[], String, String> {
        @Override
        protected String doInBackground(byte[]... jpeg) {
            File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
            if(photo.exists()) {
                photo.delete();
            }

            try {
                FileOutputStream fos = new FileOutputStream(photo.getPath());
                fos.write(jpeg[0]);
                fos.close();
            }
            catch (java.io.IOException e) {
                Log.e("MainActivity", "Exception in photoCallback", e);
            }

            return(null);
        }
    }
}

更新

至于例外我得到,如果我试图做的主要功能如下面的code,

As for the exceptions I was getting, if I tried making the main function like the code below,

public void onCreate(Bundle savedInstanceState)
{
    //Call the parent class
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    preview = (SurfaceView) findViewById(R.id.preview);
    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    Camera.Parameters parameters = camera.getParameters();
    parameters.setPictureFormat(PixelFormat.JPEG);
    camera.setParameters(parameters);

    try {
        //Start the camera preview display
        camera.setPreviewDisplay(previewHolder);
        camera.startPreview();
    } 
    catch (IOException ex) {
        Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
    }
}

我得到应用程序已意外停止,请重试。我基本上是试图遵循的步骤是,<一个href=\"http://developer.android.com/reference/android/hardware/Camera.html#set$p$pviewDisplay(android.view.SurfaceHolder)\"相对=nofollow>安卓机制的文档指定。我也试图把这个code到onResume功能的摄像机对象被检索后,再调用this.onResume。

I get "The application has stopped unexpectedly. Please Try again." I was basically trying to follow the steps that the android documention specifies. I also tried putting this code into the onResume function after the camera object is retrieved, and then calling this.onResume.

推荐答案

如果你需要的就是打开一个摄像头,拍照,并获得图像的东西。
那么你可以这样做:
启动相机使用意图

If what you need is just open up a camera, take a picture, and get the image. then you can do: launch Camera using Intents

您高于code是集成版本。相机集成到您的应用程序。
我不知道,如果你有真正的Andr​​oid设备进行测试。
该模拟器会显示黑色或更换中的实际照相机机器人图标画面。

Your above code is the integrated version. That integrates the camera into your app. I am not sure if you have the real android device to test. The simulator will show either black or "android icon" screen in replacing the real camera.

所以测试它真实的设备,如果你没有。

so test it on real device if you weren't.

和你能对你有?

这篇关于你如何获得一个简单的摄像头程序为Android的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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