カテゴリー
SugiBlog Webエンジニアのためのお役立ちTips

写真オートフォーカス撮影

この記事は最終更新日から1年以上経過しています。

カメラ撮影でオートフォーカスを実装します。
撮影した画像は、SDカードに保存します。
サムネイルは自動的に作成され、ギャラリーにも登録されます。

【HelloCameraActivity.java】

package android.test.camera;

import android.app.Activity;
import android.os.Bundle;
import android.view.*;

public class HelloCameraActivity extends Activity {

    private AutoFocusPreview mPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mPreview = new AutoFocusPreview(this);
        setContentView(mPreview);
    }

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

    @Override
    protected void onPause() {
        super.onPause();
    }

}

【CameraPreview.java】

package android.test.camera;

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

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.ErrorCallback;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    protected Context context;
    private SurfaceHolder holder;
    protected Camera camera;

    CameraPreview(Context context) {
        super(context);
        this.context = context;
        holder = getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d("TEST", "surfaceCreated");
        if (camera == null) {
            try {
                camera = Camera.open();
            } catch (RuntimeException e) {
                ((Activity)context).finish();
                Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        if (camera != null) {
            camera.setPreviewCallback(new PreviewCallback() {
                @Override
                public void onPreviewFrame(byte[] data, Camera camera) {
                    Log.d("TEST", "onPreviewFrame: preview: data=" + data);
                }
            });
            camera.setOneShotPreviewCallback(new PreviewCallback() {
                @Override
                public void onPreviewFrame(byte[] data, Camera camera) {
                    Log.d("TEST", "onPreviewFrame: short preview: data=" + data);
                }
            });
            camera.setErrorCallback(new ErrorCallback() {
                @Override
                public void onError(int error, Camera camera) {
                    Log.d("TEST", "onError: error=" + error);
                }
            });
        }
        try {
            camera.setPreviewDisplay(holder);
        } catch (IOException e) {
            camera.release();
            camera = null;
            ((Activity)context).finish();
            Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d("TEST", "surfaceChanged");
        if (camera == null) {
            ((Activity)context).finish();
        } else {
            camera.stopPreview();
            setPictureFormat(format);
            setPreviewSize(width, height);
            camera.startPreview();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d("TEST", "surfaceDestroyed");
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    protected void setPictureFormat(int format) {
        try {
            Camera.Parameters params = camera.getParameters();
            List<Integer> supported = params.getSupportedPictureFormats();
            if (supported != null) {
                for (int f : supported) {
                    if (f == format) {
                        params.setPreviewFormat(format);
                        camera.setParameters(params);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void setPreviewSize(int width, int height) {
        Camera.Parameters params = camera.getParameters();
        List<Camera.Size> supported = params.getSupportedPreviewSizes();
        if (supported != null) {
            for (Camera.Size size : supported) {
                if (size.width <= width && size.height <= height) {
                    params.setPreviewSize(size.width, size.height);
                    camera.setParameters(params);
                    break;
                }
            }
        }
    }

    protected void setAntibanding(String antibanding) {
        Camera.Parameters params = camera.getParameters();
        List<String> supported = params.getSupportedAntibanding();
        if (supported != null) {
            for (String ab : supported) {
                if (ab.equals(antibanding)) {
                    params.setAntibanding(antibanding);
                    camera.setParameters(params);
                    break;
                }
            }
        }
    }

    protected void setColorEffect(String effect) {
        Camera.Parameters params = camera.getParameters();
        List<String> supported = params.getSupportedColorEffects();
        if (supported != null) {
            for (String e : supported) {
                if (e.equals(effect)) {
                    params.setColorEffect(effect);
                    camera.setParameters(params);
                    break;
                }
            }
        }
    }

    protected void setFlashMode(String flash_mode) {
        Camera.Parameters params = camera.getParameters();
        List<String> supported = params.getSupportedFlashModes();
        if (supported != null) {
            for (String fm : supported) {
                if (fm.equals(flash_mode)) {
                    params.setFlashMode(flash_mode);
                    camera.setParameters(params);
                    break;
                }
            }
        }
    }

    protected void setFocusMode(String focus_mode) {
        Camera.Parameters params = camera.getParameters();
        List<String> supported = params.getSupportedFocusModes();
        if (supported != null) {
            for (String fm : supported) {
                if (fm.equals(focus_mode)) {
                    params.setFocusMode(focus_mode);
                    camera.setParameters(params);
                    break;
                }
            }
        }
    }

    protected void setSceneMode(String scene_mode) {
        Camera.Parameters params = camera.getParameters();
        List<String> supported = params.getSupportedSceneModes();
        if (supported != null) {
            for (String sm : supported) {
                if (sm.equals(scene_mode)) {
                    params.setSceneMode(scene_mode);
                    camera.setParameters(params);
                    break;
                }
            }
        }
    }

    protected void setWhiteBalance(String white_balance) {
        Camera.Parameters params = camera.getParameters();
        List<String> supported = params.getSupportedWhiteBalance();
        if (supported != null) {
            for (String wb : supported) {
                if (wb.equals(white_balance)) {
                    params.setWhiteBalance(white_balance);
                    camera.setParameters(params);
                    break;
                }
            }
        }
    }

}

【AutoFocusPreview.java】

package android.test.camera;

import android.os.Environment;
import java.io.*;
import android.view.*;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.format.DateFormat;
import android.util.Log;

public class AutoFocusPreview extends CameraPreview {

    private static final String TAG = "ImageManager";   
    private static final Uri IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;   
    private static final String PATH = Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera";

    AutoFocusPreview(Context context) {
        super(context);
    }

    void autoFocus() {
        camera.autoFocus(new AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, final Camera camera) {
                ShutterCallback shutter = new ShutterCallback() {
                    @Override
                    public void onShutter() {
                        Log.d("TEST", "onShutter");
                    }
                };
                PictureCallback raw = new PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        Log.d("TEST", "onPictureTaken: raw: data=" + data);
                    }
                };
                PictureCallback jpeg = new PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        // 保存する処理
                        //カメラのイメージ
                        Bitmap cameraMap = BitmapFactory.decodeByteArray(data, 0,
                            data.length, null);
                        //空のイメージを作成
                        Bitmap offBitmap = Bitmap.createBitmap(cameraMap.getWidth(),
                            cameraMap.getHeight(), Bitmap.Config.ARGB_8888);
                        Canvas offScreen = new Canvas(offBitmap);
                        offScreen.drawBitmap(
                                cameraMap,
                                null,
                                new Rect(0, 0, cameraMap.getWidth(), cameraMap.getHeight()), null);

                        // 簡単に保存    "sample"はタイトル
                        MediaStore.Images.Media.insertImage(getContext().getContentResolver(),
                            offBitmap, "sample", null);
                        // ファイル名など、パラメータを指定して保存
                        addImageAsApplication(getContext().getContentResolver(), offBitmap);
                    }
                };

                new Thread() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                        camera.startPreview();
                    }
                }.start();
            }
        });
    }

    void cancelAutoFocus() {
        camera.cancelAutoFocus();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        autoFocus();
        return true;
    }

    private static String createName(long dateTaken) {
        return DateFormat.format("yyyy-MM-dd_kk.mm.ss", dateTaken).toString();
    }

    public static Uri addImageAsApplication(ContentResolver cr, Bitmap bitmap) {
        long dateTaken = System.currentTimeMillis();
        String name = createName(dateTaken) + ".jpg";
        return addImageAsApplication(cr, name, dateTaken, PATH, name, bitmap, null);
    }

    public static Uri addImageAsApplication(ContentResolver cr, String name,
            long dateTaken, String directory,
            String filename, Bitmap source, byte[] jpegData) {

        OutputStream outputStream = null;
        String filePath = directory + "/" + filename;
        try {
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
                Log.d(TAG, dir.toString() + " create");
            }
            File file = new File(directory, filename);
            if (file.createNewFile()) {
                outputStream = new FileOutputStream(file);
                if (source != null) {
                    source.compress(CompressFormat.JPEG, 75, outputStream);
                } else {
                    outputStream.write(jpegData);
                }
            }

        } catch (FileNotFoundException ex) {
            Log.w(TAG, ex);
            return null;
        } catch (IOException ex) {
            Log.w(TAG, ex);
            return null;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Throwable t) {
                }
            }
        }

        ContentValues values = new ContentValues(5);
        values.put(Images.Media.TITLE, name);
        values.put(Images.Media.DISPLAY_NAME, filename);
        values.put(Images.Media.DATE_TAKEN, dateTaken);
        values.put(Images.Media.MIME_TYPE, "image/jpeg");
        values.put(Images.Media.DATA, filePath);
        return cr.insert(IMAGE_URI, values);
    }

}
この記事がお役に立ちましたらシェアお願いします
6,581 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です