Example usage for android.graphics ImageFormat NV21

List of usage examples for android.graphics ImageFormat NV21

Introduction

In this page you can find the example usage for android.graphics ImageFormat NV21.

Prototype

int NV21

To view the source code for android.graphics ImageFormat NV21.

Click Source Link

Document

YCrCb format used for images, which uses the NV21 encoding format.

Usage

From source file:hr.abunicic.angular.CameraActivity.java

/**
 * Method that starts detection of shapes.
 *//*  w  ww .j  a  va  2  s.co  m*/
public void startDetection() {
    startPreview = !startPreview;

    mCamera.startPreview();
    mCamera.setPreviewCallback(new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {

            //Getting engine results
            VisionEngineResults res = JobScheduler.getEngineResults();
            if (res != null) {
                rp = res;

                updateDescription();
            }

            if (inScheduler < 3 && startPreview) {

                inScheduler++;

                cornersView.setVisibility(View.VISIBLE);

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                params = mCamera.getParameters();
                Camera.Size size = params.getPreviewSize();

                //Compressing frame image to JPEG and then to byte array
                YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
                Rect rectangle = new Rect();
                rectangle.bottom = size.height;
                rectangle.top = 0;
                rectangle.left = 0;
                rectangle.right = size.width;
                yuvImage.compressToJpeg(rectangle, 20, out);
                byte[] imageBytes = out.toByteArray();

                //Starting the PrepareTask for this frame
                new PrepareTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageBytes);
                /*
                                    Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes , 0, imageBytes.length);
                                    try {
                Matrix matrix = new Matrix();
                        
                matrix.postRotate(90);
                        
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(),true);
                        
                Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);
                //storeImage(rotatedBitmap);
                if (mRecognizer.getCurrentState().equals(Recognizer.State.READY)) {
                    mRecognizer.recognizeBitmap(rotatedBitmap, Orientation.ORIENTATION_LANDSCAPE_RIGHT, CameraActivity.this);
                }
                                    } catch (IllegalStateException e) {
                        
                                    }
                */

                if (croppedBitmap != null) {
                    if (mRecognizer.getCurrentState().equals(Recognizer.State.READY)) {
                        storeImage(croppedBitmap);
                        mRecognizer.recognizeBitmap(croppedBitmap, Orientation.ORIENTATION_LANDSCAPE_RIGHT,
                                CameraActivity.this);
                    }
                } else {

                }

                camera.startPreview();

            } else if (!startPreview) {
                cornersView.setVisibility(View.GONE);
            }

        }
    });
}

From source file:com.almalence.opencam.SavingService.java

public void saveResultPictureNew(long sessionID) {
    if (ApplicationScreen.getForceFilename() != null) {
        saveResultPicture(sessionID);//from  w ww . j  av a  2 s . c  o  m
        return;
    }

    initSavingPrefs();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // save fused result
    try {
        DocumentFile saveDir = getSaveDirNew(false);

        int imagesAmount = Integer
                .parseInt(getFromSharedMem("amountofresultframes" + Long.toString(sessionID)));

        if (imagesAmount == 0)
            imagesAmount = 1;

        int imageIndex = 0;
        String sImageIndex = getFromSharedMem("resultframeindex" + Long.toString(sessionID));
        if (sImageIndex != null)
            imageIndex = Integer.parseInt(getFromSharedMem("resultframeindex" + Long.toString(sessionID)));

        if (imageIndex != 0)
            imagesAmount = 1;

        ContentValues values = null;

        boolean hasDNGResult = false;
        for (int i = 1; i <= imagesAmount; i++) {
            hasDNGResult = false;
            String format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));

            if (format != null && format.equalsIgnoreCase("dng"))
                hasDNGResult = true;

            String idx = "";

            if (imagesAmount != 1)
                idx += "_" + ((format != null && !format.equalsIgnoreCase("dng") && hasDNGResult)
                        ? i - imagesAmount / 2
                        : i);

            String modeName = getFromSharedMem("modeSaveName" + Long.toString(sessionID));

            // define file name format. from settings!
            String fileFormat = getExportFileName(modeName);
            fileFormat += idx;

            DocumentFile file = null;
            if (ApplicationScreen.getForceFilename() == null) {
                if (hasDNGResult) {
                    file = saveDir.createFile("image/x-adobe-dng", fileFormat + ".dng");
                } else {
                    file = saveDir.createFile("image/jpeg", fileFormat);
                }
            } else {
                file = DocumentFile.fromFile(ApplicationScreen.getForceFilename());
            }

            // Create buffer image to deal with exif tags.
            OutputStream os = null;
            File bufFile = new File(getApplicationContext().getFilesDir(), "buffer.jpeg");
            try {
                os = new FileOutputStream(bufFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Take only one result frame from several results
            // Used for PreShot plugin that may decide which result to save
            if (imagesAmount == 1 && imageIndex != 0) {
                i = imageIndex;
                //With changed frame index we have to get appropriate frame format
                format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));
            }

            String resultOrientation = getFromSharedMem(
                    "resultframeorientation" + i + Long.toString(sessionID));
            int orientation = 0;
            if (resultOrientation != null)
                orientation = Integer.parseInt(resultOrientation);

            String resultMirrored = getFromSharedMem("resultframemirrored" + i + Long.toString(sessionID));
            Boolean cameraMirrored = false;
            if (resultMirrored != null)
                cameraMirrored = Boolean.parseBoolean(resultMirrored);

            int x = Integer.parseInt(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            int y = Integer.parseInt(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
            if (orientation == 0 || orientation == 180 || (format != null && format.equalsIgnoreCase("dng"))) {
                x = Integer.valueOf(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
                y = Integer.valueOf(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            }

            Boolean writeOrientationTag = true;
            String writeOrientTag = getFromSharedMem("writeorientationtag" + Long.toString(sessionID));
            if (writeOrientTag != null)
                writeOrientationTag = Boolean.parseBoolean(writeOrientTag);

            if (format != null && format.equalsIgnoreCase("jpeg")) {// if result in jpeg format

                if (os != null) {
                    byte[] frame = SwapHeap.SwapFromHeap(
                            Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID))),
                            Integer.parseInt(
                                    getFromSharedMem("resultframelen" + i + Long.toString(sessionID))));
                    os.write(frame);
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (format != null && format.equalsIgnoreCase("dng")
                    && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                saveDNGPicture(i, sessionID, os, x, y, orientation, cameraMirrored);
            } else {// if result in nv21 format
                int yuv = Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID)));
                com.almalence.YuvImage out = new com.almalence.YuvImage(yuv, ImageFormat.NV21, x, y, null);
                Rect r;

                String res = getFromSharedMem("resultfromshared" + Long.toString(sessionID));
                if ((null == res) || "".equals(res) || "true".equals(res)) {
                    // to avoid problems with SKIA
                    int cropHeight = out.getHeight() - out.getHeight() % 16;
                    r = new Rect(0, 0, out.getWidth(), cropHeight);
                } else {
                    if (null == getFromSharedMem("resultcrop0" + Long.toString(sessionID))) {
                        // to avoid problems with SKIA
                        int cropHeight = out.getHeight() - out.getHeight() % 16;
                        r = new Rect(0, 0, out.getWidth(), cropHeight);
                    } else {
                        int crop0 = Integer
                                .parseInt(getFromSharedMem("resultcrop0" + Long.toString(sessionID)));
                        int crop1 = Integer
                                .parseInt(getFromSharedMem("resultcrop1" + Long.toString(sessionID)));
                        int crop2 = Integer
                                .parseInt(getFromSharedMem("resultcrop2" + Long.toString(sessionID)));
                        int crop3 = Integer
                                .parseInt(getFromSharedMem("resultcrop3" + Long.toString(sessionID)));

                        r = new Rect(crop0, crop1, crop0 + crop2, crop1 + crop3);
                    }
                }

                jpegQuality = Integer.parseInt(prefs.getString(ApplicationScreen.sJPEGQualityPref, "95"));
                if (!out.compressToJpeg(r, jpegQuality, os)) {
                    ApplicationScreen.getMessageHandler()
                            .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
                    return;
                }
                SwapHeap.FreeFromHeap(yuv);
            }

            String orientation_tag = String.valueOf(0);
            //            int sensorOrientation = CameraController.getSensorOrientation(CameraController.getCameraIndex());
            //            int displayOrientation = CameraController.getDisplayOrientation();
            ////            sensorOrientation = (360 + sensorOrientation + (cameraMirrored ? -displayOrientation
            ////                  : displayOrientation)) % 360;
            //            if (cameraMirrored) displayOrientation = -displayOrientation;
            //            
            //            // Calculate desired JPEG orientation relative to camera orientation to make
            //            // the image upright relative to the device orientation
            //            orientation = (sensorOrientation + displayOrientation + 360) % 360;

            switch (orientation) {
            default:
            case 0:
                orientation_tag = String.valueOf(0);
                break;
            case 90:
                orientation_tag = cameraMirrored ? String.valueOf(270) : String.valueOf(90);
                break;
            case 180:
                orientation_tag = String.valueOf(180);
                break;
            case 270:
                orientation_tag = cameraMirrored ? String.valueOf(90) : String.valueOf(270);
                break;
            }

            int exif_orientation = ExifInterface.ORIENTATION_NORMAL;
            if (writeOrientationTag) {
                switch ((orientation + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            } else {
                switch ((additionalRotationValue + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            }

            if (!enableExifTagOrientation)
                exif_orientation = ExifInterface.ORIENTATION_NORMAL;

            values = new ContentValues();
            values.put(ImageColumns.TITLE,
                    file.getName().substring(0,
                            file.getName().lastIndexOf(".") >= 0 ? file.getName().lastIndexOf(".")
                                    : file.getName().length()));
            values.put(ImageColumns.DISPLAY_NAME, file.getName());
            values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
            values.put(ImageColumns.MIME_TYPE, "image/jpeg");

            if (enableExifTagOrientation) {
                if (writeOrientationTag) {
                    values.put(ImageColumns.ORIENTATION, String.valueOf(
                            (Integer.parseInt(orientation_tag) + additionalRotationValue + 360) % 360));
                } else {
                    values.put(ImageColumns.ORIENTATION, String.valueOf((additionalRotationValue + 360) % 360));
                }
            } else {
                values.put(ImageColumns.ORIENTATION, String.valueOf(0));
            }

            String filePath = file.getName();

            // If we able to get File object, than get path from it.
            // fileObject should not be null for files on phone memory.
            File fileObject = Util.getFileFromDocumentFile(file);
            if (fileObject != null) {
                filePath = fileObject.getAbsolutePath();
                values.put(ImageColumns.DATA, filePath);
            } else {
                // This case should typically happen for files saved to SD
                // card.
                String documentPath = Util.getAbsolutePathFromDocumentFile(file);
                values.put(ImageColumns.DATA, documentPath);
            }

            if (!enableExifTagOrientation && !hasDNGResult) {
                Matrix matrix = new Matrix();
                if (writeOrientationTag && (orientation + additionalRotationValue) != 0) {
                    matrix.postRotate((orientation + additionalRotationValue + 360) % 360);
                    rotateImage(bufFile, matrix);
                } else if (!writeOrientationTag && additionalRotationValue != 0) {
                    matrix.postRotate((additionalRotationValue + 360) % 360);
                    rotateImage(bufFile, matrix);
                }
            }

            if (useGeoTaggingPrefExport) {
                Location l = MLocation.getLocation(getApplicationContext());
                if (l != null) {
                    double lat = l.getLatitude();
                    double lon = l.getLongitude();
                    boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
                    if (hasLatLon) {
                        values.put(ImageColumns.LATITUDE, l.getLatitude());
                        values.put(ImageColumns.LONGITUDE, l.getLongitude());
                    }
                }
            }

            File modifiedFile = null;
            if (!hasDNGResult) {
                modifiedFile = saveExifTags(bufFile, sessionID, i, x, y, exif_orientation,
                        useGeoTaggingPrefExport, enableExifTagOrientation);
            }
            if (modifiedFile != null) {
                bufFile.delete();

                if (ApplicationScreen.getForceFilename() == null) {
                    // Copy buffer image with exif tags into result file.
                    InputStream is = null;
                    int len;
                    byte[] buf = new byte[4096];
                    try {
                        os = getApplicationContext().getContentResolver().openOutputStream(file.getUri());
                        is = new FileInputStream(modifiedFile);
                        while ((len = is.read(buf)) > 0) {
                            os.write(buf, 0, len);
                        }
                        is.close();
                        os.close();
                    } catch (IOException eIO) {
                        eIO.printStackTrace();
                        final IOException eIOFinal = eIO;
                        ApplicationScreen.instance.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(MainScreen.getMainContext(),
                                        "Error ocurred:" + eIOFinal.getLocalizedMessage(), Toast.LENGTH_LONG)
                                        .show();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    copyToForceFileName(modifiedFile);
                }

                modifiedFile.delete();
            } else {
                // Copy buffer image into result file.
                InputStream is = null;
                int len;
                byte[] buf = new byte[4096];
                try {
                    os = getApplicationContext().getContentResolver().openOutputStream(file.getUri());
                    is = new FileInputStream(bufFile);
                    while ((len = is.read(buf)) > 0) {
                        os.write(buf, 0, len);
                    }
                    is.close();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bufFile.delete();
            }

            Uri uri = getApplicationContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
                    values);
            broadcastNewPicture(uri);
        }

        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    } catch (IOException e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler()
                .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    }
}

From source file:com.almalence.opencam.PluginManagerBase.java

public void saveInputFile(boolean isYUV, Long SessionID, int i, byte[] buffer, int yuvBuffer,
        String fileFormat) {/* w w  w.jav a2 s.c o m*/
    // if Android 5+ use new saving method.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        saveInputFileNew(isYUV, SessionID, i, buffer, yuvBuffer, fileFormat);
        return;
    }

    CameraController.Size imageSize = CameraController.getCameraImageSize();
    ContentValues values = null;
    String resultOrientation = getFromSharedMem("frameorientation" + (i + 1) + Long.toString(SessionID));
    if (resultOrientation == null) {
        resultOrientation = getFromSharedMem("frameorientation" + i + Long.toString(SessionID));
    }

    String resultMirrored = getFromSharedMem("framemirrored" + (i + 1) + Long.toString(SessionID));
    if (resultMirrored == null) {
        resultMirrored = getFromSharedMem("framemirrored" + i + Long.toString(SessionID));
    }
    Boolean cameraMirrored = false;
    if (resultMirrored != null)
        cameraMirrored = Boolean.parseBoolean(resultMirrored);

    int mDisplayOrientation = 0;
    if (resultOrientation != null) {
        mDisplayOrientation = Integer.parseInt(resultOrientation);
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());
    boolean saveGeoInfo = prefs.getBoolean("useGeoTaggingPrefExport", false);

    File saveDir = getSaveDir(false);
    File file = new File(saveDir, fileFormat + ".jpg");
    FileOutputStream os = null;

    try {
        try {
            os = new FileOutputStream(file);
        } catch (Exception e) {
            // save always if not working saving to sdcard
            e.printStackTrace();
            saveDir = getSaveDir(true);
            file = new File(saveDir, fileFormat + ".jpg");

            os = new FileOutputStream(file);
        }
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        if (os != null) {
            if (!isYUV) {
                os.write(buffer);
            } else {
                jpegQuality = Integer.parseInt(prefs.getString(MainScreen.sJPEGQualityPref, "95"));

                com.almalence.YuvImage image = new com.almalence.YuvImage(yuvBuffer, ImageFormat.NV21,
                        imageSize.getWidth(), imageSize.getHeight(), null);
                // to avoid problems with SKIA
                int cropHeight = image.getHeight() - image.getHeight() % 16;
                image.compressToJpeg(new Rect(0, 0, image.getWidth(), cropHeight), jpegQuality, os);

                mDisplayOrientation = saveExifToInput(file, mDisplayOrientation, cameraMirrored, saveGeoInfo);
            }
            os.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    values = new ContentValues();
    values.put(ImageColumns.TITLE, file.getName().substring(0, file.getName().lastIndexOf(".")));
    values.put(ImageColumns.DISPLAY_NAME, file.getName());
    values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
    values.put(ImageColumns.MIME_TYPE, "image/jpeg");
    values.put(ImageColumns.ORIENTATION, mDisplayOrientation);
    values.put(ImageColumns.DATA, file.getAbsolutePath());

    if (saveGeoInfo) {
        Location l = MLocation.getLocation(ApplicationScreen.getMainContext());

        if (l != null) {
            values.put(ImageColumns.LATITUDE, l.getLatitude());
            values.put(ImageColumns.LONGITUDE, l.getLongitude());
        }
    }

    ApplicationScreen.instance.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}

From source file:com.almalence.opencam.PluginManagerBase.java

private void saveInputFileNew(boolean isYUV, Long SessionID, int i, byte[] buffer, int yuvBuffer,
        String fileFormat) {/*from  www  . j ava 2s.  c om*/

    int mImageWidth = Integer.parseInt(PluginManager.getInstance().getFromSharedMem("imageWidth" + SessionID));
    int mImageHeight = Integer
            .parseInt(PluginManager.getInstance().getFromSharedMem("imageHeight" + SessionID));
    ContentValues values = null;
    String resultOrientation = getFromSharedMem("frameorientation" + (i + 1) + Long.toString(SessionID));
    if (resultOrientation == null) {
        resultOrientation = getFromSharedMem("frameorientation" + i + Long.toString(SessionID));
    }

    String resultMirrored = getFromSharedMem("framemirrored" + (i + 1) + Long.toString(SessionID));
    if (resultMirrored == null) {
        resultMirrored = getFromSharedMem("framemirrored" + i + Long.toString(SessionID));
    }

    Boolean cameraMirrored = false;
    if (resultMirrored != null)
        cameraMirrored = Boolean.parseBoolean(resultMirrored);

    int mDisplayOrientation = 0;
    if (resultOrientation != null) {
        mDisplayOrientation = Integer.parseInt(resultOrientation);
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());
    boolean saveGeoInfo = prefs.getBoolean("useGeoTaggingPrefExport", false);

    DocumentFile file;
    DocumentFile saveDir = getSaveDirNew(false);
    if (saveDir == null || !saveDir.exists()) {
        return;
    }

    file = saveDir.createFile("image/jpeg", fileFormat);
    if (file == null || !file.canWrite()) {
        return;
    }

    OutputStream os = null;
    File bufFile = new File(ApplicationScreen.instance.getFilesDir(), "buffer.jpeg");
    try {
        os = new FileOutputStream(bufFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (os != null) {
        try {
            if (!isYUV) {
                os.write(buffer);
            } else {
                jpegQuality = Integer.parseInt(prefs.getString(MainScreen.sJPEGQualityPref, "95"));

                com.almalence.YuvImage image = new com.almalence.YuvImage(yuvBuffer, ImageFormat.NV21,
                        mImageWidth, mImageHeight, null);
                // to avoid problems with SKIA
                int cropHeight = image.getHeight() - image.getHeight() % 16;
                image.compressToJpeg(new Rect(0, 0, image.getWidth(), cropHeight), jpegQuality, os);
            }
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        mDisplayOrientation = saveExifToInput(bufFile, mDisplayOrientation, cameraMirrored, saveGeoInfo);

        // Copy buffer image with exif tags into result file.
        InputStream is = null;
        int len;
        byte[] buf = new byte[1024];
        try {
            os = ApplicationScreen.instance.getContentResolver().openOutputStream(file.getUri());
            is = new FileInputStream(bufFile);
            while ((len = is.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            is.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    bufFile.delete();

    values = new ContentValues();
    values.put(ImageColumns.TITLE, file.getName().substring(0, file.getName().lastIndexOf(".")));
    values.put(ImageColumns.DISPLAY_NAME, file.getName());
    values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
    values.put(ImageColumns.MIME_TYPE, "image/jpeg");
    values.put(ImageColumns.ORIENTATION, mDisplayOrientation);

    String filePath = file.getName();
    // If we able to get File object, than get path from it.
    // fileObject should not be null for files on phone memory.
    File fileObject = Util.getFileFromDocumentFile(file);
    if (fileObject != null) {
        filePath = fileObject.getAbsolutePath();
        values.put(ImageColumns.DATA, filePath);
    } else {
        // This case should typically happen for files saved to SD
        // card.
        String documentPath = Util.getAbsolutePathFromDocumentFile(file);
        values.put(ImageColumns.DATA, documentPath);
    }

    if (saveGeoInfo) {
        Location l = MLocation.getLocation(ApplicationScreen.getMainContext());
        if (l != null) {
            values.put(ImageColumns.LATITUDE, l.getLatitude());
            values.put(ImageColumns.LONGITUDE, l.getLongitude());
        }
    }

    ApplicationScreen.instance.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}

From source file:org.mozilla.gecko.GeckoAppShell.java

static int[] initCamera(String aContentType, int aCamera, int aWidth, int aHeight) {
    Log.i(LOGTAG, "initCamera(" + aContentType + ", " + aWidth + "x" + aHeight + ") on thread "
            + Thread.currentThread().getId());

    getMainHandler().post(new Runnable() {
        public void run() {
            try {
                GeckoApp.mAppContext.enableCameraView();
            } catch (Exception e) {
            }/*from w  w  w .  j a  v  a 2  s  .com*/
        }
    });

    // [0] = 0|1 (failure/success)
    // [1] = width
    // [2] = height
    // [3] = fps
    int[] result = new int[4];
    result[0] = 0;

    if (Build.VERSION.SDK_INT >= 9) {
        if (android.hardware.Camera.getNumberOfCameras() == 0)
            return result;
    }

    try {
        // no front/back camera before API level 9
        if (Build.VERSION.SDK_INT >= 9)
            sCamera = android.hardware.Camera.open(aCamera);
        else
            sCamera = android.hardware.Camera.open();

        android.hardware.Camera.Parameters params = sCamera.getParameters();
        params.setPreviewFormat(ImageFormat.NV21);

        // use the preview fps closest to 25 fps.
        int fpsDelta = 1000;
        try {
            Iterator<Integer> it = params.getSupportedPreviewFrameRates().iterator();
            while (it.hasNext()) {
                int nFps = it.next();
                if (Math.abs(nFps - kPreferedFps) < fpsDelta) {
                    fpsDelta = Math.abs(nFps - kPreferedFps);
                    params.setPreviewFrameRate(nFps);
                }
            }
        } catch (Exception e) {
            params.setPreviewFrameRate(kPreferedFps);
        }

        // set up the closest preview size available
        Iterator<android.hardware.Camera.Size> sit = params.getSupportedPreviewSizes().iterator();
        int sizeDelta = 10000000;
        int bufferSize = 0;
        while (sit.hasNext()) {
            android.hardware.Camera.Size size = sit.next();
            if (Math.abs(size.width * size.height - aWidth * aHeight) < sizeDelta) {
                sizeDelta = Math.abs(size.width * size.height - aWidth * aHeight);
                params.setPreviewSize(size.width, size.height);
                bufferSize = size.width * size.height;
            }
        }

        try {
            sCamera.setPreviewDisplay(GeckoApp.cameraView.getHolder());
        } catch (IOException e) {
            Log.e(LOGTAG, "Error setPreviewDisplay:", e);
        } catch (RuntimeException e) {
            Log.e(LOGTAG, "Error setPreviewDisplay:", e);
        }

        sCamera.setParameters(params);
        sCameraBuffer = new byte[(bufferSize * 12) / 8];
        sCamera.addCallbackBuffer(sCameraBuffer);
        sCamera.setPreviewCallbackWithBuffer(new android.hardware.Camera.PreviewCallback() {
            public void onPreviewFrame(byte[] data, android.hardware.Camera camera) {
                cameraCallbackBridge(data);
                if (sCamera != null)
                    sCamera.addCallbackBuffer(sCameraBuffer);
            }
        });
        sCamera.startPreview();
        params = sCamera.getParameters();
        Log.i(LOGTAG, "Camera: " + params.getPreviewSize().width + "x" + params.getPreviewSize().height + " @ "
                + params.getPreviewFrameRate() + "fps. format is " + params.getPreviewFormat());
        result[0] = 1;
        result[1] = params.getPreviewSize().width;
        result[2] = params.getPreviewSize().height;
        result[3] = params.getPreviewFrameRate();

        Log.i(LOGTAG, "Camera preview started");
    } catch (RuntimeException e) {
        Log.e(LOGTAG, "initCamera RuntimeException : ", e);
        result[0] = result[1] = result[2] = result[3] = 0;
    }
    return result;
}