Example usage for android.support.v4.provider DocumentFile getUri

List of usage examples for android.support.v4.provider DocumentFile getUri

Introduction

In this page you can find the example usage for android.support.v4.provider DocumentFile getUri.

Prototype

public abstract Uri getUri();

Source Link

Usage

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

private void prepareMediaRecorder() {
    mMediaRecorder = CameraController.getMediaRecorder();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH && videoStabilization)
        CameraController.setVideoStabilization(true);

    CameraController.unlockCamera();/*www.  j  a va  2 s  .c o  m*/

    // Step 2: Set sources
    if (!CameraController.isUseCamera2()) {
        CameraController.configureMediaRecorder(mMediaRecorder);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    } else {
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    }

    if (ApplicationScreen.isMicrophonePermissionGranted())
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);

    int quality = Integer.parseInt(
            prefs.getString(CameraController.getCameraIndex() == 0 ? ApplicationScreen.sImageSizeVideoBackPref
                    : ApplicationScreen.sImageSizeVideoFrontPref, DEFAULT_VIDEO_QUALITY));

    if (maxQuality()) {
        quality = CamcorderProfile.QUALITY_HIGH;
    }

    boolean useProfile = true;
    if (!CamcorderProfile.hasProfile(CameraController.getCameraIndex(), quality))
        useProfile = false;

    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    try {
        try {
            if (swChecked) {
                int qualityTimeLapse = quality;
                // if time lapse activated
                switch (quality) {
                case CamcorderProfile.QUALITY_QCIF:
                    quality = CamcorderProfile.QUALITY_TIME_LAPSE_QCIF;
                    break;
                case CamcorderProfile.QUALITY_CIF:
                    quality = CamcorderProfile.QUALITY_TIME_LAPSE_CIF;
                    break;
                case CamcorderProfile.QUALITY_2160P:
                    quality = CamcorderProfile.QUALITY_TIME_LAPSE_2160P;
                    break;
                case CamcorderProfile.QUALITY_1080P:
                    quality = CamcorderProfile.QUALITY_TIME_LAPSE_1080P;
                    break;
                case CamcorderProfile.QUALITY_720P:
                    quality = CamcorderProfile.QUALITY_TIME_LAPSE_720P;
                    break;
                case CamcorderProfile.QUALITY_480P:
                    quality = CamcorderProfile.QUALITY_TIME_LAPSE_480P;
                    break;
                case QUALITY_4K:
                    quality = QUALITY_4K;
                    break;
                case CamcorderProfile.QUALITY_HIGH:
                    quality = CamcorderProfile.QUALITY_TIME_LAPSE_HIGH;
                    break;
                default:
                    break;
                }
                if (!CamcorderProfile.hasProfile(CameraController.getCameraIndex(), quality)) {
                    Toast.makeText(ApplicationScreen.instance, "Time lapse not supported", Toast.LENGTH_LONG)
                            .show();
                } else
                    quality = qualityTimeLapse;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Video", "Time lapse error catched" + e.getMessage());
            swChecked = false;
        }

        lastUseProfile = useProfile;
        if (useProfile) {
            CamcorderProfile pr = CamcorderProfile.get(CameraController.getCameraIndex(), quality);
            if (ApplicationScreen.isMicrophonePermissionGranted()) {
                mMediaRecorder.setProfile(pr);
            } else {
                // If we don't have access to microphone, then configure only video settings of MediaREcorder.
                mMediaRecorder.setOutputFormat(pr.fileFormat);
                mMediaRecorder.setVideoEncoder(pr.videoCodec);
                mMediaRecorder.setVideoSize(pr.videoFrameWidth, pr.videoFrameHeight);
                mMediaRecorder.setVideoFrameRate(pr.videoFrameRate);
                mMediaRecorder.setVideoEncodingBitRate(pr.videoBitRate);
            }
            lastCamcorderProfile = pr;
        } else {
            boolean useProf = false;
            lastUseProf = useProf;
            CameraController.Size sz = null;
            switch (quality) {
            case CamcorderProfile.QUALITY_QCIF:
                sz = new CameraController.Size(176, 144);
                break;
            case CamcorderProfile.QUALITY_CIF:
                sz = new CameraController.Size(352, 288);
                break;
            case CamcorderProfile.QUALITY_480P:
                sz = new CameraController.Size(640, 480);
                break;
            case CamcorderProfile.QUALITY_720P:
                sz = new CameraController.Size(1280, 720);
                break;
            case CamcorderProfile.QUALITY_1080P:
                sz = new CameraController.Size(1920, 1080);
                break;
            case CamcorderProfile.QUALITY_2160P: {
                if (CamcorderProfile.hasProfile(CameraController.getCameraIndex(),
                        CamcorderProfile.QUALITY_2160P))
                    sz = new CameraController.Size(3840, 2160);
                else {
                    CamcorderProfile prof = CamcorderProfile.get(CameraController.getCameraIndex(),
                            CamcorderProfile.QUALITY_HIGH);
                    prof.videoFrameWidth = 3840;
                    prof.videoFrameHeight = 2160;
                    prof.videoBitRate = (int) (prof.videoBitRate * 2.8); // need a higher bitrate for the better quality - this is roughly based on the bitrate used by an S5's native camera app at 4K (47.6 Mbps, compared to 16.9 Mbps which is what's returned by the QUALITY_HIGH profile)
                    if (ApplicationScreen.isMicrophonePermissionGranted()) {
                        mMediaRecorder.setProfile(prof);
                    } else {
                        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
                        mMediaRecorder.setVideoSize(prof.videoFrameWidth, prof.videoFrameHeight);
                        mMediaRecorder.setVideoFrameRate(30);
                        mMediaRecorder.setVideoEncodingBitRate((int) (prof.videoBitRate * 2.8)); // need a higher bitrate for the better quality
                    }
                    lastCamcorderProfile = prof;
                    useProf = true;
                    lastUseProf = useProf;
                }

            }
                break;
            case QUALITY_4K: {
                if (CamcorderProfile.hasProfile(CameraController.getCameraIndex(),
                        CamcorderProfile.QUALITY_1080P)) {
                    CamcorderProfile prof = CamcorderProfile.get(CamcorderProfile.QUALITY_1080P);
                    prof.videoFrameHeight = 2160;
                    prof.videoFrameWidth = 4096;
                    if (ApplicationScreen.isMicrophonePermissionGranted()) {
                        mMediaRecorder.setProfile(prof);
                    } else {
                        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
                        mMediaRecorder.setVideoSize(prof.videoFrameWidth, prof.videoFrameHeight);
                        mMediaRecorder.setVideoFrameRate(30);
                        mMediaRecorder.setVideoEncodingBitRate(prof.videoBitRate * 4); // 2160p has 4x more pixels then 1080p.
                    }
                    lastCamcorderProfile = prof;
                    useProf = true;
                    lastUseProf = useProf;
                } else
                    sz = new CameraController.Size(4096, 2160);
            }
                break;
            default:
                break;
            }

            if (!useProf) {
                mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
                mMediaRecorder.setVideoSize(sz.getWidth(), sz.getHeight());
                mMediaRecorder.setVideoFrameRate(30);

                // Other parameters just copy from CamcorderProfile.QUALITY_1080P
                CamcorderProfile prof = CamcorderProfile.get(CamcorderProfile.QUALITY_1080P);
                mMediaRecorder.setVideoEncodingBitRate(prof.videoBitRate * 4); // 2160p has 4x more pixels then 1080p.

                if (ApplicationScreen.isMicrophonePermissionGranted()) {
                    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                    mMediaRecorder.setAudioChannels(prof.audioChannels);
                    mMediaRecorder.setAudioEncodingBitRate(prof.audioBitRate);
                    mMediaRecorder.setAudioSamplingRate(prof.audioSampleRate);
                }

                lastSz = sz;
            } else
                lastUseProfile = true;
        }

        if (swChecked) {
            double val1 = Double.valueOf(stringInterval[interval]);
            int val2 = measurementVal;
            switch (val2) {
            case 0:
                val2 = 1;
                break;
            case 1:
                val2 = 60;
                break;
            case 2:
                val2 = 3600;
                break;
            default:
                break;
            }
            captureRate = 1 / (val1 * val2);
            mMediaRecorder.setCaptureRate(captureRate);
        }
    } catch (Exception e) {
        e.printStackTrace();

        releaseMediaRecorder(); // release the MediaRecorder object
        return;
    }

    // Step 4: Set output file
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile file = getOutputMediaDocumentFile();
        try {
            documentFileSavedFd = ApplicationScreen.instance.getContentResolver()
                    .openFileDescriptor(file.getUri(), "w");
            FileDescriptor fileDescriptor = documentFileSavedFd.getFileDescriptor();
            mMediaRecorder.setOutputFile(fileDescriptor);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mMediaRecorder.setOutputFile(getOutputMediaFile().toString());
        }
    } else {
        mMediaRecorder.setOutputFile(getOutputMediaFile().toString());
    }

    // Step 5: Set the preview output
    if (!CameraController.isUseCamera2()) {
        mMediaRecorder.setPreviewDisplay(ApplicationScreen.getPreviewSurfaceHolder().getSurface());
    }

    mMediaRecorder.setOrientationHint(CameraController.isFrontCamera()
            ? (ApplicationScreen.getWantLandscapePhoto()
                    ? ApplicationScreen.getGUIManager().getImageDataOrientation()
                    : (ApplicationScreen.getGUIManager().getImageDataOrientation() + 180) % 360)
            : ApplicationScreen.getGUIManager().getImageDataOrientation());

    // Step 6: Prepare configured MediaRecorder
    try {
        mMediaRecorder.prepare();
    } catch (Exception e) {
        Log.d("Video", "Exception preparing MediaRecorder: " + e.getMessage());
        releaseMediaRecorder();

        CameraController.lockCamera(); // take camera access back from MediaRecorder
        return;
    }
}

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

private void saveInputFileNew(boolean isYUV, Long SessionID, int i, byte[] buffer, int yuvBuffer,
        String fileFormat) {/* w w w .j  a  v  a  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:com.almalence.plugins.capture.video.VideoCapturePlugin.java

protected void doExportVideo() {
    boolean onPause = this.onPause;
    this.onPause = false;
    boolean isDro = this.modeDRO();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && (documentFileSaved != null || !isDro)) {
        DocumentFile fileSaved = VideoCapturePlugin.documentFileSaved;
        ArrayList<DocumentFile> filesListToExport = documentFilesList;
        String resultName = fileSaved.getName();
        DocumentFile resultFile = fileSaved;

        if (filesListToExport.size() > 0) {
            int inputFileCount = filesListToExport.size();
            if (!onPause)
                inputFileCount++;//from w  w w . j a va 2  s. c  o m

            DocumentFile[] inputFiles = new DocumentFile[inputFileCount];

            for (int i = 0; i < filesListToExport.size(); i++) {
                inputFiles[i] = filesListToExport.get(i);
            }

            // If video recording hadn't been paused before STOP was
            // pressed, then last recorded file is not in the list with
            // other files, added to list of files manually.
            if (!onPause) {
                inputFiles[inputFileCount - 1] = fileSaved;
            }

            resultFile = appendNew(inputFiles);

            // Remove merged files, except first one, because it stores the
            // result of merge.
            for (int i = 0; i < filesListToExport.size(); i++) {
                DocumentFile currentFile = filesListToExport.get(i);
                currentFile.delete();
            }

            // If video recording hadn't been paused before STOP was
            // pressed, then last recorded file is not in the list with
            // other files, and should be deleted manually.
            if (!onPause)
                fileSaved.delete();

            String tmpName = resultFile.getName();
            if (resultFile.renameTo(resultName))
                ;

            // Make sure, that there won't be duplicate broken file
            // in phone memory at gallery.
            String args[] = { tmpName };
            ApplicationScreen.instance.getContentResolver().delete(Video.Media.EXTERNAL_CONTENT_URI,
                    Video.Media.DISPLAY_NAME + "=?", args);
        }

        String name = resultFile.getName();
        String data = null;
        // If we able to get File object, than get path from it. Gallery
        // doesn't show the file, if it's stored at phone memory and
        // we need insert new file to gallery manually.
        File file = Util.getFileFromDocumentFile(resultFile);
        if (file != null) {
            data = file.getAbsolutePath();
        } else {
            // This case should typically happen for files saved to SD
            // card.
            data = Util.getAbsolutePathFromDocumentFile(resultFile);
        }

        if (data != null) {
            values.put(VideoColumns.DISPLAY_NAME, name);
            values.put(VideoColumns.DATA, data);
            Uri uri = ApplicationScreen.instance.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
                    values);
            ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
        }
    } else {
        File fileSaved = VideoCapturePlugin.fileSaved;
        ArrayList<File> filesListToExport = filesList;

        File firstFile = fileSaved;

        if (filesListToExport.size() > 0) {
            firstFile = filesListToExport.get(0);

            int inputFileCount = filesListToExport.size();
            if (!onPause)
                inputFileCount++;

            File[] inputFiles = new File[inputFileCount];

            for (int i = 0; i < filesListToExport.size(); i++) {
                inputFiles[i] = filesListToExport.get(i);
            }

            if (!onPause)
                inputFiles[inputFileCount - 1] = fileSaved;

            File resultFile = append(inputFiles);

            for (int i = 0; i < filesListToExport.size(); i++) {
                File currentFile = filesListToExport.get(i);
                currentFile.delete();
            }

            if (resultFile != null) {
                if (!resultFile.getAbsoluteFile().equals(fileSaved.getAbsoluteFile())) {
                    fileSaved.delete();
                    resultFile.renameTo(fileSaved);
                }
            }
        }

        filesListToExport.clear();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && isDro) {
            DocumentFile outputFile = getOutputMediaDocumentFile();
            File file = Util.getFileFromDocumentFile(outputFile);

            if (file != null) {
                // Don't do anything with ouputFile. It's useless, remove
                // it.
                outputFile.delete();
                Uri uri = ApplicationScreen.instance.getContentResolver()
                        .insert(Video.Media.EXTERNAL_CONTENT_URI, values);
                ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
            } else {
                // Copy result file from phone memory to selected folder at
                // SD-card.
                InputStream is = null;
                int len;
                byte[] buf = new byte[4096];
                try {
                    OutputStream os = ApplicationScreen.instance.getContentResolver()
                            .openOutputStream(outputFile.getUri());
                    is = new FileInputStream(firstFile);
                    while ((len = is.read(buf)) > 0) {
                        os.write(buf, 0, len);
                    }
                    is.close();
                    os.close();
                    firstFile.delete();

                    // Make sure, that there won't be duplicate broken file
                    // in phone memory at gallery.
                    String args[] = { firstFile.getAbsolutePath() };
                    ApplicationScreen.instance.getContentResolver().delete(Video.Media.EXTERNAL_CONTENT_URI,
                            Video.Media.DATA + "=?", args);

                    String data = Util.getAbsolutePathFromDocumentFile(outputFile);
                    if (data != null) {
                        values.put(VideoColumns.DATA, data);
                        Uri uri = ApplicationScreen.instance.getContentResolver()
                                .insert(Video.Media.EXTERNAL_CONTENT_URI, values);
                        ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            Uri uri = ApplicationScreen.instance.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
                    values);
            ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
        }
    }

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);

}

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

public void saveResultPictureNew(long sessionID) {
    if (ApplicationScreen.getForceFilename() != null) {
        saveResultPicture(sessionID);//from  w ww . j a  v 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);
    }
}