Example usage for android.media ExifInterface ORIENTATION_NORMAL

List of usage examples for android.media ExifInterface ORIENTATION_NORMAL

Introduction

In this page you can find the example usage for android.media ExifInterface ORIENTATION_NORMAL.

Prototype

int ORIENTATION_NORMAL

To view the source code for android.media ExifInterface ORIENTATION_NORMAL.

Click Source Link

Usage

From source file:com.tealeaf.TeaLeaf.java

protected void onActivityResult(int request, int result, Intent data) {
    super.onActivityResult(request, result, data);
    PluginManager.callAll("onActivityResult", request, result, data);
    logger.log("GOT ACTIVITY RESULT WITH", request, result);

    switch (request) {
    case PhotoPicker.CAPTURE_IMAGE:
        if (result == RESULT_OK) {
            EventQueue.pushEvent(new PhotoBeginLoadedEvent());
            Bitmap bmp = null;// w ww . j av a 2 s.c  o  m

            if (data != null) {
                Bundle extras = data.getExtras();
                //try and get bitmap off of intent
                if (extras != null) {
                    bmp = (Bitmap) extras.get("data");
                }

            }

            //try the large file on disk
            final File f = PhotoPicker.getCaptureImageTmpFile();
            if (f != null && f.exists()) {
                new Thread(new Runnable() {
                    public void run() {
                        Bitmap bmp = null;
                        String filePath = f.getAbsolutePath();

                        try {
                            bmp = BitmapFactory.decodeFile(filePath);
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 4;
                            bmp = BitmapFactory.decodeFile(filePath, options);
                        }

                        if (bmp != null) {
                            try {
                                File f = new File(filePath);
                                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                        ExifInterface.ORIENTATION_NORMAL);
                                if (orientation != ExifInterface.ORIENTATION_NORMAL) {
                                    int rotateBy = 0;
                                    switch (orientation) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        rotateBy = ROTATE_90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        rotateBy = ROTATE_180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        rotateBy = ROTATE_270;
                                        break;
                                    }
                                    Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy);
                                    if (rotatedBmp != bmp) {
                                        bmp.recycle();
                                    }
                                    bmp = rotatedBmp;
                                }
                            } catch (Exception e) {
                                logger.log(e);
                            }
                            f.delete();

                            if (bmp != null) {
                                glView.getTextureLoader()
                                        .saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                                glView.getTextureLoader().finishCameraPicture();
                            } else {
                                glView.getTextureLoader().failedCameraPicture();
                            }
                        }
                    }
                }).start();

            } else {
                glView.getTextureLoader().saveCameraPhoto(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                glView.getTextureLoader().finishCameraPicture();
            }
        } else {
            glView.getTextureLoader().failedCameraPicture();
        }
        break;
    case PhotoPicker.PICK_IMAGE:
        if (result == RESULT_OK) {
            final Uri selectedImage = data.getData();
            EventQueue.pushEvent(new PhotoBeginLoadedEvent());

            String[] filePathColumn = { MediaColumns.DATA, MediaStore.Images.ImageColumns.ORIENTATION };

            String _filepath = null;

            try {
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                _filepath = cursor.getString(columnIndex);
                columnIndex = cursor.getColumnIndex(filePathColumn[1]);
                int orientation = cursor.getInt(columnIndex);
                cursor.close();
            } catch (Exception e) {

            }

            final String filePath = _filepath;

            new Thread(new Runnable() {
                public void run() {
                    if (filePath == null) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        InputStream inputStream;
                        Bitmap bmp = null;

                        try {
                            inputStream = getContentResolver().openInputStream(selectedImage);
                            bmp = BitmapFactory.decodeStream(inputStream, null, options);
                            inputStream.close();
                        } catch (Exception e) {
                            logger.log(e);

                        }

                        if (bmp != null) {
                            glView.getTextureLoader()
                                    .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                            glView.getTextureLoader().finishGalleryPicture();
                        } else {
                            glView.getTextureLoader().failedGalleryPicture();
                        }

                    } else {
                        Bitmap bmp = null;

                        try {
                            bmp = BitmapFactory.decodeFile(filePath);
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 4;
                            bmp = BitmapFactory.decodeFile(filePath, options);
                        }

                        if (bmp != null) {
                            try {
                                File f = new File(filePath);
                                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                        ExifInterface.ORIENTATION_NORMAL);
                                if (orientation != ExifInterface.ORIENTATION_NORMAL) {
                                    int rotateBy = 0;
                                    switch (orientation) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        rotateBy = ROTATE_90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        rotateBy = ROTATE_180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        rotateBy = ROTATE_270;
                                        break;
                                    }
                                    Bitmap rotatedBmp = rotateBitmap(bmp, rotateBy);
                                    if (rotatedBmp != bmp) {
                                        bmp.recycle();
                                    }
                                    bmp = rotatedBmp;
                                }
                            } catch (Exception e) {
                                logger.log(e);
                            }

                            if (bmp != null) {
                                glView.getTextureLoader()
                                        .saveGalleryPicture(glView.getTextureLoader().getCurrentPhotoId(), bmp);
                                glView.getTextureLoader().finishGalleryPicture();
                            } else {
                                glView.getTextureLoader().failedGalleryPicture();
                            }
                        }
                    }
                }
            }).start();

        } else {
            glView.getTextureLoader().failedGalleryPicture();
        }
        break;
    }
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

/**
 * Called when the camera view exits.//from   w w w .  jav  a  2s.  co  m
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    Log.d(LOG_TAG, "-z");

    // If retrieving photo from library
    if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        Log.d(LOG_TAG, "-y");
        if (resultCode == Activity.RESULT_OK) {
            Log.d(LOG_TAG, "-x");
            Uri uri = intent.getData();
            Log.d(LOG_TAG, "-w");
            // If you ask for video or all media type you will automatically
            // get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                Log.d(LOG_TAG, "mediaType not PICTURE, so must be Video");

                String metadataDateTime = "";
                ExifInterface exif;
                try {
                    exif = new ExifInterface(this.getRealPathFromURI(uri, this.cordova));
                    if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) {
                        Log.d(LOG_TAG, "z4a");
                        metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString();
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                    }
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }

                Log.d(LOG_TAG, "before create thumbnail");
                Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(
                        (new File(this.getRealPathFromURI(uri, this.cordova))).getAbsolutePath(),
                        MediaStore.Images.Thumbnails.MINI_KIND);
                Log.d(LOG_TAG, "after create thumbnail");
                String mid = generateRandomMid();

                try {
                    String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_"
                            + mid + ".jpg";
                    FileOutputStream foMedium = new FileOutputStream(filePathMedium);
                    bitmap.compress(CompressFormat.JPEG, 100, foMedium);
                    foMedium.flush();
                    foMedium.close();

                    bitmap.recycle();
                    System.gc();

                    JSONObject mediaFile = new JSONObject();
                    try {
                        mediaFile.put("mid", mid);
                        mediaFile.put("mediaType", "video");
                        mediaFile.put("filePath", filePathMedium);
                        mediaFile.put("filePathMedium", filePathMedium);
                        mediaFile.put("filePathThumb", filePathMedium);
                        mediaFile.put("typeOfPluginResult", "initialRecordInformer");
                        String absolutePath = (new File(this.getRealPathFromURI(uri, this.cordova)))
                                .getAbsolutePath();
                        mediaFile.put("fileExt", absolutePath.substring(absolutePath.lastIndexOf(".") + 1));
                        if (metadataDateTime != "") {
                            mediaFile.put("metadataDateTime", metadataDateTime);
                        }
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "error: " + e.getStackTrace().toString());
                    }
                    Log.d(LOG_TAG, "mediafile at 638" + mediaFile.toString());
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                            (new JSONArray()).put(mediaFile));
                    pluginResult.setKeepCallback(true);
                    this.callbackContext.sendPluginResult(pluginResult);
                    new UploadVideoToS3Task().execute(new File(this.getRealPathFromURI(uri, this.cordova)),
                            this.callbackContext, mid, mediaFile);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                String imagePath = this.getRealPathFromURI(uri, this.cordova);
                String mimeType = FileUtils.getMimeType(imagePath);
                // If we don't have a valid image so quit.
                if (imagePath == null || mimeType == null || !(mimeType.equalsIgnoreCase("image/jpeg")
                        || mimeType.equalsIgnoreCase("image/png"))) {
                    Log.d(LOG_TAG, "I either have a null image path or bitmap");
                    this.failPicture("Unable to retrieve path to picture!");
                    return;
                }

                String mid = generateRandomMid();

                Log.d(LOG_TAG, "a");

                JSONObject mediaFile = new JSONObject();

                Log.d(LOG_TAG, "b");

                try {
                    FileInputStream fi = new FileInputStream(imagePath);
                    Bitmap bitmap = BitmapFactory.decodeStream(fi);
                    fi.close();

                    Log.d(LOG_TAG, "z1");

                    // try to get exif data
                    ExifInterface exif = new ExifInterface(imagePath);

                    Log.d(LOG_TAG, "z2");

                    JSONObject metadataJson = new JSONObject();

                    Log.d(LOG_TAG, "z3");

                    /*
                    JSONObject latlng = new JSONObject();
                    String lat = "0";
                    String lng = "0";
                    if (exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) != null) {
                       lat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
                    }
                    if (exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) != null) {
                       lng = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
                    }
                    latlng.put("lat", lat);
                    latlng.put("lng", lng);
                    Log.d(LOG_TAG, "z4");
                    metadataJson.put("locationData", latlng);
                    */

                    String metadataDateTime = "";

                    if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) {
                        Log.d(LOG_TAG, "z4a");
                        JSONObject exifWrapper = new JSONObject();
                        exifWrapper.put("DateTimeOriginal",
                                exif.getAttribute(ExifInterface.TAG_DATETIME).toString());
                        exifWrapper.put("DateTimeDigitized",
                                exif.getAttribute(ExifInterface.TAG_DATETIME).toString());
                        metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString();
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        Log.d(LOG_TAG, "z5");
                        metadataJson.put("Exif", exifWrapper);
                    }
                    Log.d(LOG_TAG, "z6");

                    Log.d(LOG_TAG, "metadataJson: " + metadataJson.toString());
                    Log.d(LOG_TAG, "metadataDateTime: " + metadataDateTime.toString());

                    if (exif.getAttribute(ExifInterface.TAG_ORIENTATION) != null) {
                        int o = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION));

                        Log.d(LOG_TAG, "z7");

                        if (o == ExifInterface.ORIENTATION_NORMAL) {
                            rotate = 0;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_90) {
                            rotate = 90;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_180) {
                            rotate = 180;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_270) {
                            rotate = 270;
                        } else {
                            rotate = 0;
                        }

                        Log.d(LOG_TAG, "z8");

                        Log.d(LOG_TAG, "rotate: " + rotate);

                        // try to correct orientation
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            Log.d(LOG_TAG, "z9");
                            matrix.setRotate(rotate);
                            Log.d(LOG_TAG, "z10");
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                            Log.d(LOG_TAG, "z11");
                        }
                    }

                    Log.d(LOG_TAG, "c");

                    String filePath = this.getTempDirectoryPath(this.cordova.getActivity()) + "/econ_" + mid
                            + ".jpg";
                    FileOutputStream foEcon = new FileOutputStream(filePath);
                    fitInsideSquare(bitmap, 850).compress(CompressFormat.JPEG, 45, foEcon);
                    foEcon.flush();
                    foEcon.close();

                    Log.d(LOG_TAG, "d");

                    String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_"
                            + mid + ".jpg";
                    FileOutputStream foMedium = new FileOutputStream(filePathMedium);
                    makeInsideSquare(bitmap, 320).compress(CompressFormat.JPEG, 55, foMedium);
                    foMedium.flush();
                    foMedium.close();

                    Log.d(LOG_TAG, "e");

                    String filePathThumb = this.getTempDirectoryPath(this.cordova.getActivity()) + "/thumb_"
                            + mid + ".jpg";
                    FileOutputStream foThumb = new FileOutputStream(filePathThumb);
                    makeInsideSquare(bitmap, 175).compress(CompressFormat.JPEG, 55, foThumb);
                    foThumb.flush();
                    foThumb.close();

                    bitmap.recycle();
                    System.gc();

                    Log.d(LOG_TAG, "f");

                    mediaFile.put("mid", mid);
                    mediaFile.put("mediaType", "photo");
                    mediaFile.put("filePath", filePath);
                    mediaFile.put("filePathMedium", filePath);
                    mediaFile.put("filePathThumb", filePath);
                    mediaFile.put("typeOfPluginResult", "initialRecordInformer");
                    //mediaFile.put("metadataJson", metadataJson);
                    if (metadataDateTime != "") {
                        mediaFile.put("metadataDateTime", metadataDateTime);
                    }

                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                            (new JSONArray()).put(mediaFile));
                    pluginResult.setKeepCallback(true);
                    this.callbackContext.sendPluginResult(pluginResult);
                    Log.d(LOG_TAG, "g");
                    Log.d(LOG_TAG, "mediaFile " + mediaFile.toString());
                    new UploadFilesToS3Task().execute(new File(filePath), new File(filePathMedium),
                            new File(filePathThumb), this.callbackContext, mid, mediaFile);
                    Log.d(LOG_TAG, "h");
                } catch (FileNotFoundException e) {
                    Log.d(LOG_TAG, "error: " + e.getStackTrace().toString());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    Log.d(LOG_TAG, "error: " + e1.getStackTrace().toString());
                } catch (JSONException e2) {
                    // TODO Auto-generated catch block
                    Log.d(LOG_TAG, "error: " + e2.getStackTrace().toString());
                }

                /*
                if (this.correctOrientation) {
                   String[] cols = { MediaStore.Images.Media.ORIENTATION };
                   Cursor cursor = this.cordova
                .getActivity()
                .getContentResolver()
                .query(intent.getData(), cols, null, null,
                      null);
                   if (cursor != null) {
                      cursor.moveToPosition(0);
                      rotate = cursor.getInt(0);
                      cursor.close();
                   }
                   if (rotate != 0) {
                      Matrix matrix = new Matrix();
                      matrix.setRotate(rotate);
                      bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                   bitmap.getWidth(), bitmap.getHeight(),
                   matrix, true);
                   }
                }
                        
                // Create an ExifHelper to save the exif
                // data that is lost during compression
                String resizePath = this
                      .getTempDirectoryPath(this.cordova
                   .getActivity())
                      + "/resize.jpg";
                ExifHelper exif = new ExifHelper();
                try {
                   if (this.encodingType == JPEG) {
                      exif.createInFile(resizePath);
                      exif.readExifData();
                      rotate = exif.getOrientation();
                   }
                } catch (IOException e) {
                   e.printStackTrace();
                }
                        
                OutputStream os = new FileOutputStream(
                      resizePath);
                bitmap.compress(Bitmap.CompressFormat.JPEG,
                      this.mQuality, os);
                os.close();
                        
                // Restore exif data to file
                if (this.encodingType == JPEG) {
                   exif.createOutFile(this
                .getRealPathFromURI(uri,
                      this.cordova));
                   exif.writeExifData();
                }
                        
                if (bitmap != null) {
                   bitmap.recycle();
                   bitmap = null;
                }
                System.gc();
                        
                // The resized image is cached by the app in
                // order to get around this and not have to
                // delete your
                // application cache I'm adding the current
                // system time to the end of the file url.
                this.callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis());
                */
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:com.netcompss.ffmpeg4android_client.BaseWizard.java

@SuppressWarnings("unused")
private String reporteds(String path) {

    ExifInterface exif = null;// w  w w  .ja va 2s  .  c o m
    try {
        exif = new ExifInterface(path);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }

    if (path != null) {

        if (path.contains("http")) {
            try {
                URL url = new URL(path);
                HttpGet httpRequest = null;

                httpRequest = new HttpGet(url.toURI());

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                InputStream input = bufHttpEntity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(input);
                input.close();
                return getPath(bitmap);
            } catch (MalformedURLException e) {
                Log.e("ImageActivity", "bad url", e);
            } catch (Exception e) {
                Log.e("ImageActivity", "io error", e);
            }
        } else {
            Options options = new Options();
            options.inSampleSize = 2;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(getApplicationContext().getResources(), srcBgId, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, w, h);
            Bitmap unbgbtmp = BitmapFactory.decodeResource(getApplicationContext().getResources(), srcBgId,
                    options);
            Bitmap unrlbtmp = ScalingUtilities.decodeFile(path, w, h, ScalingLogic.FIT);
            unrlbtmp.recycle();
            Bitmap rlbtmp = null;
            if (unrlbtmp != null) {
                rlbtmp = ScalingUtilities.createScaledBitmap(unrlbtmp, w, h, ScalingLogic.FIT);
            }
            if (unbgbtmp != null && rlbtmp != null) {
                Bitmap bgbtmp = ScalingUtilities.createScaledBitmap(unbgbtmp, w, h, ScalingLogic.FIT);
                Bitmap newscaledBitmap = ProcessingBitmapTwo(bgbtmp, rlbtmp);
                unbgbtmp.recycle();
                return getPath(newscaledBitmap);
            }
        }
    }
    return path;

}

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

public void saveResultPictureNew(long sessionID) {
    if (ApplicationScreen.getForceFilename() != null) {
        saveResultPicture(sessionID);/*from   w  ww  .  j ava2 s .com*/
        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.yk.notification.util.BitmapUtil.java

/**
 * ?/* www .  ja  v a 2  s.  c  om*/
 * 
 * @param path
 *            ?
 * @return 
 */
public static int getImageDegree(String path) {
    int degree = 0;
    try {
        ExifInterface exifInterface = new ExifInterface(path);
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            degree = 90;
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            degree = 180;
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            degree = 270;
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return degree;
}

From source file:com.nextgis.ngm_clink_monitoring.fragments.CreateObjectFragment.java

protected void writePhotoAttach(File tempPhotoFile) throws IOException {
    GISApplication app = (GISApplication) getActivity().getApplication();

    ContentResolver contentResolver = app.getContentResolver();
    String photoFileName = getPhotoFileName(tempPhotoFile);
    Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), photoFileName: " + photoFileName);

    Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName
            + "/" + mObjectId + "/attach");
    Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), allAttachesUri: " + allAttachesUri);

    ContentValues values = new ContentValues();
    values.put(VectorLayer.ATTACH_DISPLAY_NAME, photoFileName);
    values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg");
    //values.put(VectorLayer.ATTACH_DESCRIPTION, photoFileName);

    Uri attachUri = null;/* w w  w  . j av  a 2  s . com*/
    String insertAttachError = null;
    try {
        attachUri = contentResolver.insert(allAttachesUri, values);
        Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), insert: " + attachUri.toString());
    } catch (Exception e) {
        Log.d(TAG,
                "CreateObjectFragment, writePhotoAttach(), Insert attach failed: " + e.getLocalizedMessage());
        insertAttachError = "Insert attach failed: " + e.getLocalizedMessage();
    }

    if (null != attachUri) {
        int exifOrientation = BitmapUtil.getOrientationFromExif(tempPhotoFile);

        // resize and rotate
        Bitmap sourceBitmap = BitmapFactory.decodeFile(tempPhotoFile.getPath());
        Bitmap resizedBitmap = BitmapUtil.getResizedBitmap(sourceBitmap, FoclConstants.PHOTO_MAX_SIZE_PX,
                FoclConstants.PHOTO_MAX_SIZE_PX);
        Bitmap rotatedBitmap = BitmapUtil.rotateBitmap(resizedBitmap, exifOrientation);

        // jpeg compress
        File tempAttachFile = File.createTempFile("attach", null, app.getCacheDir());
        OutputStream tempOutStream = new FileOutputStream(tempAttachFile);
        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, FoclConstants.PHOTO_JPEG_COMPRESS_QUALITY,
                tempOutStream);
        tempOutStream.close();

        int newHeight = rotatedBitmap.getHeight();
        int newWidth = rotatedBitmap.getWidth();

        rotatedBitmap.recycle();

        // write EXIF to new file
        BitmapUtil.copyExifData(tempPhotoFile, tempAttachFile);
        BitmapUtil.writeLocationToExif(tempAttachFile, mAccurateLocation, app.getGpsTimeOffset());

        ExifInterface attachExif = new ExifInterface(tempAttachFile.getCanonicalPath());

        attachExif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL);
        attachExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, "" + newHeight);
        attachExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, "" + newWidth);

        attachExif.saveAttributes();

        // attach data from tempAttachFile
        OutputStream attachOutStream = contentResolver.openOutputStream(attachUri);
        if (attachOutStream != null) {
            FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream);
            attachOutStream.close();
        } else {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), attachOutStream == null, attachUri"
                    + attachUri.toString());
        }

        if (!tempAttachFile.delete()) {
            Log.d(TAG,
                    "CreateObjectFragment, writePhotoAttach(), tempAttachFile.delete() failed, tempAttachFile:"
                            + tempAttachFile.getAbsolutePath());
        }
    }

    if (app.isOriginalPhotoSaving()) {
        BitmapUtil.writeLocationToExif(tempPhotoFile, mAccurateLocation, app.getGpsTimeOffset());
        File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName);

        if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), move original failed, tempPhotoFile:"
                    + tempPhotoFile.getAbsolutePath() + ", origPhotoFile: " + origPhotoFile.getAbsolutePath());
            throw new IOException(
                    "Save original photo failed, tempPhotoFile: " + tempPhotoFile.getAbsolutePath());
        }

    } else {
        if (!tempPhotoFile.delete()) {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), tempPhotoFile.delete() failed, tempPhotoFile:"
                    + tempPhotoFile.getAbsolutePath());
        }
    }

    if (null != insertAttachError) {
        throw new IOException(insertAttachError);
    }
}

From source file:org.telegram.ui.Components.ChatAttachAlert.java

public ChatAttachAlert(Context context, final ChatActivity parentFragment) {
    super(context, false);
    baseFragment = parentFragment;//  w  ww. j av  a2s . c  o  m
    setDelegate(this);
    setUseRevealAnimation(true);
    checkCamera(false);
    if (deviceHasGoodCamera) {
        CameraController.getInstance().initCamera();
    }
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.albumsDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadInlineHints);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.cameraInitied);
    shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow);

    containerView = listView = new RecyclerListView(context) {

        private int lastWidth;
        private int lastHeight;

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (cameraAnimationInProgress) {
                return true;
            } else if (cameraOpened) {
                return processTouchEvent(ev);
            } else if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY != 0
                    && ev.getY() < scrollOffsetY) {
                dismiss();
                return true;
            }
            return super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (cameraAnimationInProgress) {
                return true;
            } else if (cameraOpened) {
                return processTouchEvent(event);
            }
            return !isDismissed() && super.onTouchEvent(event);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int height = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21) {
                height -= AndroidUtilities.statusBarHeight;
            }
            int contentSize = backgroundPaddingTop + AndroidUtilities.dp(294)
                    + (SearchQuery.inlineBots.isEmpty() ? 0
                            : ((int) Math.ceil(SearchQuery.inlineBots.size() / 4.0f) * AndroidUtilities.dp(100)
                                    + AndroidUtilities.dp(12)));
            int padding = contentSize == AndroidUtilities.dp(294) ? 0
                    : Math.max(0, (height - AndroidUtilities.dp(294)));
            if (padding != 0 && contentSize < height) {
                padding -= (height - contentSize);
            }
            if (padding == 0) {
                padding = backgroundPaddingTop;
            }
            if (getPaddingTop() != padding) {
                ignoreLayout = true;
                setPadding(backgroundPaddingLeft, padding, backgroundPaddingLeft, 0);
                ignoreLayout = false;
            }
            super.onMeasure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(Math.min(contentSize, height), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int width = right - left;
            int height = bottom - top;

            int newPosition = -1;
            int newTop = 0;

            int count = listView.getChildCount();
            int lastVisibleItemPosition = -1;
            int lastVisibleItemPositionTop = 0;
            if (count > 0) {
                View child = listView.getChildAt(listView.getChildCount() - 1);
                Holder holder = (Holder) listView.findContainingViewHolder(child);
                if (holder != null) {
                    lastVisibleItemPosition = holder.getAdapterPosition();
                    lastVisibleItemPositionTop = child.getTop();
                }
            }

            if (lastVisibleItemPosition >= 0 && height - lastHeight != 0) {
                newPosition = lastVisibleItemPosition;
                newTop = lastVisibleItemPositionTop + height - lastHeight - getPaddingTop();
            }

            super.onLayout(changed, left, top, right, bottom);

            if (newPosition != -1) {
                ignoreLayout = true;
                layoutManager.scrollToPositionWithOffset(newPosition, newTop);
                super.onLayout(false, left, top, right, bottom);
                ignoreLayout = false;
            }

            lastHeight = height;
            lastWidth = width;

            updateLayout();
            checkCameraViewPosition();
        }

        @Override
        public void onDraw(Canvas canvas) {
            if (useRevealAnimation && Build.VERSION.SDK_INT <= 19) {
                canvas.save();
                canvas.clipRect(backgroundPaddingLeft, scrollOffsetY,
                        getMeasuredWidth() - backgroundPaddingLeft, getMeasuredHeight());
                if (revealAnimationInProgress) {
                    canvas.drawCircle(revealX, revealY, revealRadius, ciclePaint);
                } else {
                    canvas.drawRect(backgroundPaddingLeft, scrollOffsetY,
                            getMeasuredWidth() - backgroundPaddingLeft, getMeasuredHeight(), ciclePaint);
                }
                canvas.restore();
            } else {
                shadowDrawable.setBounds(0, scrollOffsetY - backgroundPaddingTop, getMeasuredWidth(),
                        getMeasuredHeight());
                shadowDrawable.draw(canvas);
            }
        }

        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            checkCameraViewPosition();
        }
    };

    listView.setWillNotDraw(false);
    listView.setClipToPadding(false);
    listView.setLayoutManager(layoutManager = new LinearLayoutManager(getContext()));
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    listView.setAdapter(adapter = new ListAdapter(context));
    listView.setVerticalScrollBarEnabled(false);
    listView.setEnabled(true);
    listView.setGlowColor(0xfff5f6f7);
    listView.addItemDecoration(new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = 0;
            outRect.right = 0;
            outRect.top = 0;
            outRect.bottom = 0;
        }
    });

    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (listView.getChildCount() <= 0) {
                return;
            }
            if (hintShowed) {
                if (layoutManager.findLastVisibleItemPosition() > 1) {
                    hideHint();
                    hintShowed = false;
                    ApplicationLoader.applicationContext
                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit()
                            .putBoolean("bothint", true).commit();
                }
            }
            updateLayout();
            checkCameraViewPosition();
        }
    });
    containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0);

    attachView = new FrameLayout(context) {
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(294), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int width = right - left;
            int height = bottom - top;
            int t = AndroidUtilities.dp(8);
            attachPhotoRecyclerView.layout(0, t, width, t + attachPhotoRecyclerView.getMeasuredHeight());
            progressView.layout(0, t, width, t + progressView.getMeasuredHeight());
            lineView.layout(0, AndroidUtilities.dp(96), width,
                    AndroidUtilities.dp(96) + lineView.getMeasuredHeight());
            hintTextView.layout(width - hintTextView.getMeasuredWidth() - AndroidUtilities.dp(5),
                    height - hintTextView.getMeasuredHeight() - AndroidUtilities.dp(5),
                    width - AndroidUtilities.dp(5), height - AndroidUtilities.dp(5));

            int diff = (width - AndroidUtilities.dp(85 * 4 + 20)) / 3;
            for (int a = 0; a < 8; a++) {
                int y = AndroidUtilities.dp(105 + 95 * (a / 4));
                int x = AndroidUtilities.dp(10) + (a % 4) * (AndroidUtilities.dp(85) + diff);
                views[a].layout(x, y, x + views[a].getMeasuredWidth(), y + views[a].getMeasuredHeight());
            }
        }
    };

    views[8] = attachPhotoRecyclerView = new RecyclerListView(context);
    attachPhotoRecyclerView.setVerticalScrollBarEnabled(true);
    attachPhotoRecyclerView.setAdapter(photoAttachAdapter = new PhotoAttachAdapter(context));
    attachPhotoRecyclerView.setClipToPadding(false);
    attachPhotoRecyclerView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), 0);
    attachPhotoRecyclerView.setItemAnimator(null);
    attachPhotoRecyclerView.setLayoutAnimation(null);
    attachPhotoRecyclerView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    attachView.addView(attachPhotoRecyclerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 80));
    attachPhotoLayoutManager = new LinearLayoutManager(context) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    attachPhotoLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    attachPhotoRecyclerView.setLayoutManager(attachPhotoLayoutManager);
    attachPhotoRecyclerView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @SuppressWarnings("unchecked")
        @Override
        public void onItemClick(View view, int position) {
            if (baseFragment == null || baseFragment.getParentActivity() == null) {
                return;
            }
            if (!deviceHasGoodCamera || position != 0) {
                if (deviceHasGoodCamera) {
                    position--;
                }
                if (MediaController.allPhotosAlbumEntry == null) {
                    return;
                }
                ArrayList<Object> arrayList = (ArrayList) MediaController.allPhotosAlbumEntry.photos;
                if (position < 0 || position >= arrayList.size()) {
                    return;
                }
                PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
                PhotoViewer.getInstance().openPhotoForSelect(arrayList, position, 0, ChatAttachAlert.this,
                        baseFragment);
                AndroidUtilities.hideKeyboard(baseFragment.getFragmentView().findFocus());
            } else {
                openCamera();
            }
        }
    });
    attachPhotoRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            checkCameraViewPosition();
        }
    });

    views[9] = progressView = new EmptyTextProgressView(context);
    if (Build.VERSION.SDK_INT >= 23 && getContext().checkSelfPermission(
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        progressView.setText(LocaleController.getString("PermissionStorage", R.string.PermissionStorage));
        progressView.setTextSize(16);
    } else {
        progressView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos));
        progressView.setTextSize(20);
    }
    attachView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 80));
    attachPhotoRecyclerView.setEmptyView(progressView);

    views[10] = lineView = new View(getContext()) {
        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }
    };
    lineView.setBackgroundColor(ContextCompat.getColor(context, R.color.divider));
    attachView.addView(lineView,
            new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, Gravity.TOP | Gravity.LEFT));
    CharSequence[] items = new CharSequence[] { LocaleController.getString("ChatCamera", R.string.ChatCamera),
            LocaleController.getString("ChatGallery", R.string.ChatGallery),
            LocaleController.getString("ChatVideo", R.string.ChatVideo),
            LocaleController.getString("AttachMusic", R.string.AttachMusic),
            LocaleController.getString("ChatDocument", R.string.ChatDocument),
            LocaleController.getString("AttachContact", R.string.AttachContact),
            LocaleController.getString("ChatLocation", R.string.ChatLocation), "" };
    for (int a = 0; a < 8; a++) {
        AttachButton attachButton = new AttachButton(context);
        attachButton.setTextAndIcon(items[a], Theme.attachButtonDrawables[a]);
        attachView.addView(attachButton, LayoutHelper.createFrame(85, 90, Gravity.LEFT | Gravity.TOP));
        attachButton.setTag(a);
        views[a] = attachButton;
        if (a == 7) {
            sendPhotosButton = attachButton;
            sendPhotosButton.imageView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        }
        attachButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delegate.didPressedButton((Integer) v.getTag());
            }
        });
    }

    hintTextView = new TextView(context);
    hintTextView.setBackgroundResource(R.drawable.tooltip);
    hintTextView.setTextColor(Theme.CHAT_GIF_HINT_TEXT_COLOR);
    hintTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    hintTextView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
    hintTextView.setText(LocaleController.getString("AttachBotsHelp", R.string.AttachBotsHelp));
    hintTextView.setGravity(Gravity.CENTER_VERTICAL);
    hintTextView.setVisibility(View.INVISIBLE);
    hintTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.scroll_tip, 0, 0, 0);
    hintTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    attachView.addView(hintTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 32,
            Gravity.RIGHT | Gravity.BOTTOM, 5, 0, 5, 5));

    for (int a = 0; a < 8; a++) {
        viewsCache.add(photoAttachAdapter.createHolder());
    }

    if (loading) {
        progressView.showProgress();
    } else {
        progressView.showTextView();
    }

    if (Build.VERSION.SDK_INT >= 16) {
        recordTime = new TextView(context);
        recordTime.setBackgroundResource(R.drawable.system);
        recordTime.getBackground()
                .setColorFilter(new PorterDuffColorFilter(0x66000000, PorterDuff.Mode.MULTIPLY));
        recordTime.setText("00:00");
        recordTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
        recordTime.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        recordTime.setAlpha(0.0f);
        recordTime.setTextColor(0xffffffff);
        recordTime.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(10),
                AndroidUtilities.dp(5));
        container.addView(recordTime, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16, 0, 0));

        cameraPanel = new FrameLayout(context) {
            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                int cx = getMeasuredWidth() / 2;
                int cy = getMeasuredHeight() / 2;
                int cx2;
                int cy2;
                shutterButton.layout(cx - shutterButton.getMeasuredWidth() / 2,
                        cy - shutterButton.getMeasuredHeight() / 2, cx + shutterButton.getMeasuredWidth() / 2,
                        cy + shutterButton.getMeasuredHeight() / 2);
                if (getMeasuredWidth() == AndroidUtilities.dp(100)) {
                    cx = cx2 = getMeasuredWidth() / 2;
                    cy2 = cy + cy / 2 + AndroidUtilities.dp(17);
                    cy = cy / 2 - AndroidUtilities.dp(17);
                } else {
                    cx2 = cx + cx / 2 + AndroidUtilities.dp(17);
                    cx = cx / 2 - AndroidUtilities.dp(17);
                    cy = cy2 = getMeasuredHeight() / 2;
                }
                switchCameraButton.layout(cx2 - switchCameraButton.getMeasuredWidth() / 2,
                        cy2 - switchCameraButton.getMeasuredHeight() / 2,
                        cx2 + switchCameraButton.getMeasuredWidth() / 2,
                        cy2 + switchCameraButton.getMeasuredHeight() / 2);
                for (int a = 0; a < 2; a++) {
                    flashModeButton[a].layout(cx - flashModeButton[a].getMeasuredWidth() / 2,
                            cy - flashModeButton[a].getMeasuredHeight() / 2,
                            cx + flashModeButton[a].getMeasuredWidth() / 2,
                            cy + flashModeButton[a].getMeasuredHeight() / 2);
                }
            }
        };
        cameraPanel.setVisibility(View.GONE);
        cameraPanel.setAlpha(0.0f);
        container.addView(cameraPanel,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 100, Gravity.LEFT | Gravity.BOTTOM));

        shutterButton = new ShutterButton(context);
        cameraPanel.addView(shutterButton, LayoutHelper.createFrame(84, 84, Gravity.CENTER));
        shutterButton.setDelegate(new ShutterButton.ShutterButtonDelegate() {
            @Override
            public void shutterLongPressed() {
                if (takingPhoto || baseFragment == null || baseFragment.getParentActivity() == null) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= 23) {
                    if (baseFragment.getParentActivity().checkSelfPermission(
                            Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                        baseFragment.getParentActivity()
                                .requestPermissions(new String[] { Manifest.permission.RECORD_AUDIO }, 21);
                        return;
                    }
                }
                for (int a = 0; a < 2; a++) {
                    flashModeButton[a].setAlpha(0.0f);
                }
                switchCameraButton.setAlpha(0.0f);
                cameraFile = AndroidUtilities.generateVideoPath();
                recordTime.setAlpha(1.0f);
                recordTime.setText("00:00");
                videoRecordTime = 0;
                videoRecordRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (videoRecordRunnable == null) {
                            return;
                        }
                        videoRecordTime++;
                        recordTime.setText(
                                String.format("%02d:%02d", videoRecordTime / 60, videoRecordTime % 60));
                        AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
                    }
                };
                AndroidUtilities.lockOrientation(parentFragment.getParentActivity());
                CameraController.getInstance().recordVideo(cameraView.getCameraSession(), cameraFile,
                        new CameraController.VideoTakeCallback() {
                            @Override
                            public void onFinishVideoRecording(final Bitmap thumb) {
                                if (cameraFile == null || baseFragment == null) {
                                    return;
                                }
                                PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
                                cameraPhoto = new ArrayList<>();
                                cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0,
                                        cameraFile.getAbsolutePath(), 0, true));
                                PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2,
                                        new PhotoViewer.EmptyPhotoViewerProvider() {
                                            @Override
                                            public Bitmap getThumbForPhoto(MessageObject messageObject,
                                                    TLRPC.FileLocation fileLocation, int index) {
                                                return thumb;
                                            }

                                            @TargetApi(16)
                                            @Override
                                            public boolean cancelButtonPressed() {
                                                if (cameraOpened && cameraView != null && cameraFile != null) {
                                                    cameraFile.delete();
                                                    AndroidUtilities.runOnUIThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            if (cameraView != null && !isDismissed()
                                                                    && Build.VERSION.SDK_INT >= 21) {
                                                                cameraView.setSystemUiVisibility(
                                                                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                                                                | View.SYSTEM_UI_FLAG_FULLSCREEN);
                                                            }
                                                        }
                                                    }, 1000);
                                                    CameraController.getInstance()
                                                            .startPreview(cameraView.getCameraSession());
                                                    cameraFile = null;
                                                }
                                                return true;
                                            }

                                            @Override
                                            public void sendButtonPressed(int index) {
                                                if (cameraFile == null) {
                                                    return;
                                                }
                                                AndroidUtilities
                                                        .addMediaToGallery(cameraFile.getAbsolutePath());
                                                baseFragment.sendMedia(
                                                        (MediaController.PhotoEntry) cameraPhoto.get(0),
                                                        PhotoViewer.getInstance().isMuteVideo());
                                                closeCamera(false);
                                                dismiss();
                                                cameraFile = null;
                                            }
                                        }, baseFragment);
                            }
                        });
                AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
                shutterButton.setState(ShutterButton.State.RECORDING, true);
            }

            @Override
            public void shutterCancel() {
                cameraFile.delete();
                resetRecordState();
                CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), true);
            }

            @Override
            public void shutterReleased() {
                if (takingPhoto) {
                    return;
                }
                if (shutterButton.getState() == ShutterButton.State.RECORDING) {
                    resetRecordState();
                    CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), false);
                    shutterButton.setState(ShutterButton.State.DEFAULT, true);
                    return;
                }
                cameraFile = AndroidUtilities.generatePicturePath();
                takingPhoto = CameraController.getInstance().takePicture(cameraFile,
                        cameraView.getCameraSession(), new Runnable() {
                            @Override
                            public void run() {
                                takingPhoto = false;
                                if (cameraFile == null || baseFragment == null) {
                                    return;
                                }
                                PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
                                cameraPhoto = new ArrayList<>();
                                int orientation = 0;
                                try {
                                    ExifInterface ei = new ExifInterface(cameraFile.getAbsolutePath());
                                    int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                            ExifInterface.ORIENTATION_NORMAL);
                                    switch (exif) {
                                    case ExifInterface.ORIENTATION_ROTATE_90:
                                        orientation = 90;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_180:
                                        orientation = 180;
                                        break;
                                    case ExifInterface.ORIENTATION_ROTATE_270:
                                        orientation = 270;
                                        break;
                                    }
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                                cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0,
                                        cameraFile.getAbsolutePath(), orientation, false));
                                PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2,
                                        new PhotoViewer.EmptyPhotoViewerProvider() {
                                            @TargetApi(16)
                                            @Override
                                            public boolean cancelButtonPressed() {
                                                if (cameraOpened && cameraView != null && cameraFile != null) {
                                                    cameraFile.delete();
                                                    AndroidUtilities.runOnUIThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            if (cameraView != null && !isDismissed()
                                                                    && Build.VERSION.SDK_INT >= 21) {
                                                                cameraView.setSystemUiVisibility(
                                                                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                                                                | View.SYSTEM_UI_FLAG_FULLSCREEN);
                                                            }
                                                        }
                                                    }, 1000);
                                                    CameraController.getInstance()
                                                            .startPreview(cameraView.getCameraSession());
                                                    cameraFile = null;
                                                }
                                                return true;
                                            }

                                            @Override
                                            public void sendButtonPressed(int index) {
                                                if (cameraFile == null) {
                                                    return;
                                                }
                                                AndroidUtilities
                                                        .addMediaToGallery(cameraFile.getAbsolutePath());
                                                baseFragment.sendMedia(
                                                        (MediaController.PhotoEntry) cameraPhoto.get(0), false);
                                                closeCamera(false);
                                                dismiss();
                                                cameraFile = null;
                                            }

                                            @Override
                                            public boolean scaleToFill() {
                                                return true;
                                            }
                                        }, baseFragment);
                            }
                        });
            }
        });

        switchCameraButton = new ImageView(context);
        switchCameraButton.setScaleType(ImageView.ScaleType.CENTER);
        cameraPanel.addView(switchCameraButton,
                LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.CENTER_VERTICAL));
        switchCameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (takingPhoto || cameraView == null || !cameraView.isInitied()) {
                    return;
                }
                cameraInitied = false;
                cameraView.switchCamera();
                ObjectAnimator animator = ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 0.0f)
                        .setDuration(100);
                animator.addListener(new AnimatorListenerAdapterProxy() {
                    @Override
                    public void onAnimationEnd(Animator animator) {
                        switchCameraButton.setImageResource(cameraView.isFrontface() ? R.drawable.camera_revert1
                                : R.drawable.camera_revert2);
                        ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 1.0f).setDuration(100).start();
                    }
                });
                animator.start();
            }
        });

        for (int a = 0; a < 2; a++) {
            flashModeButton[a] = new ImageView(context);
            flashModeButton[a].setScaleType(ImageView.ScaleType.CENTER);
            flashModeButton[a].setVisibility(View.INVISIBLE);
            cameraPanel.addView(flashModeButton[a],
                    LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
            flashModeButton[a].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View currentImage) {
                    if (flashAnimationInProgress || cameraView == null || !cameraView.isInitied()
                            || !cameraOpened) {
                        return;
                    }
                    String current = cameraView.getCameraSession().getCurrentFlashMode();
                    String next = cameraView.getCameraSession().getNextFlashMode();
                    if (current.equals(next)) {
                        return;
                    }
                    cameraView.getCameraSession().setCurrentFlashMode(next);
                    flashAnimationInProgress = true;
                    ImageView nextImage = flashModeButton[0] == currentImage ? flashModeButton[1]
                            : flashModeButton[0];
                    nextImage.setVisibility(View.VISIBLE);
                    setCameraFlashModeIcon(nextImage, next);
                    AnimatorSet animatorSet = new AnimatorSet();
                    animatorSet.playTogether(
                            ObjectAnimator.ofFloat(currentImage, "translationY", 0, AndroidUtilities.dp(48)),
                            ObjectAnimator.ofFloat(nextImage, "translationY", -AndroidUtilities.dp(48), 0),
                            ObjectAnimator.ofFloat(currentImage, "alpha", 1.0f, 0.0f),
                            ObjectAnimator.ofFloat(nextImage, "alpha", 0.0f, 1.0f));
                    animatorSet.setDuration(200);
                    animatorSet.addListener(new AnimatorListenerAdapterProxy() {
                        @Override
                        public void onAnimationEnd(Animator animator) {
                            flashAnimationInProgress = false;
                            currentImage.setVisibility(View.INVISIBLE);
                        }
                    });
                    animatorSet.start();
                }
            });
        }
    }
}

From source file:com.annanovas.bestprice.DashBoardEditActivity.java

private Bitmap imageProcess(Bitmap imageBitmap) {
    int width = imageBitmap.getWidth();
    int height = imageBitmap.getHeight();
    int newWidth = 1000;
    int newHeight = 1000;
    if (width > 1000) {
        double x = (double) width / 1000d;
        newHeight = (int) (height / x);
        newWidth = 1000;//from w w  w .  j  a v  a  2  s  .c o  m
    } else if (height > 1000) {
        double x = (double) height / 1000d;
        newWidth = (int) (width / x);
        newHeight = 1000;
    }
    // calculate the scale - in this case = 0.4f
    ExifInterface exif = null;
    int rotationAngle = 0;
    try {
        exif = new ExifInterface(imageUri);
        String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        // showLog("orientString:" + orientString + " DateTime:" + exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH));
        int orientation = orientString != null ? Integer.parseInt(orientString)
                : ExifInterface.ORIENTATION_NORMAL;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
            rotationAngle = 90;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
            rotationAngle = 180;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
            rotationAngle = 270;
        //  showLog("Rotation Angle:" + rotationAngle);
    } catch (IOException e) {
        // showLog("ExifInterface Failed!");
        e.printStackTrace();
    }
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    matrix.postRotate(rotationAngle);
    return Bitmap.createBitmap(imageBitmap, 0, 0, width, height, matrix, true);
}

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

protected File saveExifTags(File file, long sessionID, int i, int x, int y, int exif_orientation,
        boolean useGeoTaggingPrefExport, boolean enableExifTagOrientation) {
    addTimestamp(file, exif_orientation);

    // Set tag_model using ExifInterface.
    // If we try set tag_model using ExifDriver, then standard
    // gallery of android (Nexus 4) will crash on this file.
    // Can't figure out why, other Exif tools work fine.
    try {//  w  ww. j  a  va  2 s .  com
        ExifInterface ei = new ExifInterface(file.getAbsolutePath());
        String tag_model = getFromSharedMem("exiftag_model" + Long.toString(sessionID));
        String tag_make = getFromSharedMem("exiftag_make" + Long.toString(sessionID));
        if (tag_model == null)
            tag_model = Build.MODEL;
        ei.setAttribute(ExifInterface.TAG_MODEL, tag_model);
        if (tag_make == null)
            tag_make = Build.MANUFACTURER;
        ei.setAttribute(ExifInterface.TAG_MAKE, tag_make);
        ei.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(exif_orientation));
        ei.saveAttributes();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Open ExifDriver.
    ExifDriver exifDriver = ExifDriver.getInstance(file.getAbsolutePath());
    ExifManager exifManager = null;
    if (exifDriver != null) {
        exifManager = new ExifManager(exifDriver, getApplicationContext());
    }

    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) {
                exifManager.setGPSLocation(l.getLatitude(), l.getLongitude(), l.getAltitude());
            }

            String GPSDateString = new SimpleDateFormat("yyyy:MM:dd").format(new Date(l.getTime()));
            if (GPSDateString != null) {
                ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
                value.setBytes(GPSDateString.getBytes());
                exifDriver.getIfdGps().put(ExifDriver.TAG_GPS_DATE_STAMP, value);
            }
        }
    }

    String tag_exposure_time = getFromSharedMem("exiftag_exposure_time" + Long.toString(sessionID));
    String tag_aperture = getFromSharedMem("exiftag_aperture" + Long.toString(sessionID));
    String tag_flash = getFromSharedMem("exiftag_flash" + Long.toString(sessionID));
    String tag_focal_length = getFromSharedMem("exiftag_focal_lenght" + Long.toString(sessionID));
    String tag_iso = getFromSharedMem("exiftag_iso" + Long.toString(sessionID));
    String tag_white_balance = getFromSharedMem("exiftag_white_balance" + Long.toString(sessionID));
    String tag_spectral_sensitivity = getFromSharedMem(
            "exiftag_spectral_sensitivity" + Long.toString(sessionID));
    String tag_version = getFromSharedMem("exiftag_version" + Long.toString(sessionID));
    String tag_scene = getFromSharedMem("exiftag_scene_capture_type" + Long.toString(sessionID));
    String tag_metering_mode = getFromSharedMem("exiftag_metering_mode" + Long.toString(sessionID));

    if (exifDriver != null) {
        if (tag_exposure_time != null) {
            int[][] ratValue = ExifManager.stringToRational(tag_exposure_time);
            if (ratValue != null) {
                ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                value.setRationals(ratValue);
                exifDriver.getIfdExif().put(ExifDriver.TAG_EXPOSURE_TIME, value);
            }
        } else { // hack for expo bracketing
            tag_exposure_time = getFromSharedMem(
                    "exiftag_exposure_time" + Integer.toString(i) + Long.toString(sessionID));
            if (tag_exposure_time != null) {
                int[][] ratValue = ExifManager.stringToRational(tag_exposure_time);
                if (ratValue != null) {
                    ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                    value.setRationals(ratValue);
                    exifDriver.getIfdExif().put(ExifDriver.TAG_EXPOSURE_TIME, value);
                }
            }
        }
        if (tag_aperture != null) {
            int[][] ratValue = ExifManager.stringToRational(tag_aperture);
            if (ratValue != null) {
                ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                value.setRationals(ratValue);
                exifDriver.getIfdExif().put(ExifDriver.TAG_APERTURE_VALUE, value);
            }
        }
        if (tag_flash != null) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, Integer.parseInt(tag_flash));
            exifDriver.getIfdExif().put(ExifDriver.TAG_FLASH, value);
        }
        if (tag_focal_length != null) {
            int[][] ratValue = ExifManager.stringToRational(tag_focal_length);
            if (ratValue != null) {
                ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                value.setRationals(ratValue);
                exifDriver.getIfdExif().put(ExifDriver.TAG_FOCAL_LENGTH, value);
            }
        }
        try {
            if (tag_iso != null) {
                if (tag_iso.indexOf("ISO") > 0) {
                    tag_iso = tag_iso.substring(0, 2);
                }
                ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                        Integer.parseInt(tag_iso));
                exifDriver.getIfdExif().put(ExifDriver.TAG_ISO_SPEED_RATINGS, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (tag_scene != null) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, Integer.parseInt(tag_scene));
            exifDriver.getIfdExif().put(ExifDriver.TAG_SCENE_CAPTURE_TYPE, value);
        } else {
            int sceneMode = CameraController.getSceneMode();

            int sceneModeVal = 0;
            if (sceneMode == CameraParameters.SCENE_MODE_LANDSCAPE) {
                sceneModeVal = 1;
            } else if (sceneMode == CameraParameters.SCENE_MODE_PORTRAIT) {
                sceneModeVal = 2;
            } else if (sceneMode == CameraParameters.SCENE_MODE_NIGHT) {
                sceneModeVal = 3;
            }

            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, sceneModeVal);
            exifDriver.getIfdExif().put(ExifDriver.TAG_SCENE_CAPTURE_TYPE, value);
        }
        if (tag_white_balance != null) {
            exifDriver.getIfd0().remove(ExifDriver.TAG_LIGHT_SOURCE);

            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                    Integer.parseInt(tag_white_balance));
            exifDriver.getIfdExif().put(ExifDriver.TAG_WHITE_BALANCE, value);
            exifDriver.getIfdExif().put(ExifDriver.TAG_LIGHT_SOURCE, value);
        } else {
            exifDriver.getIfd0().remove(ExifDriver.TAG_LIGHT_SOURCE);

            int whiteBalance = CameraController.getWBMode();
            int whiteBalanceVal = 0;
            int lightSourceVal = 0;
            if (whiteBalance == CameraParameters.WB_MODE_AUTO) {
                whiteBalanceVal = 0;
                lightSourceVal = 0;
            } else {
                whiteBalanceVal = 1;
                lightSourceVal = 0;
            }

            if (whiteBalance == CameraParameters.WB_MODE_DAYLIGHT) {
                lightSourceVal = 1;
            } else if (whiteBalance == CameraParameters.WB_MODE_FLUORESCENT) {
                lightSourceVal = 2;
            } else if (whiteBalance == CameraParameters.WB_MODE_WARM_FLUORESCENT) {
                lightSourceVal = 2;
            } else if (whiteBalance == CameraParameters.WB_MODE_INCANDESCENT) {
                lightSourceVal = 3;
            } else if (whiteBalance == CameraParameters.WB_MODE_TWILIGHT) {
                lightSourceVal = 3;
            } else if (whiteBalance == CameraParameters.WB_MODE_CLOUDY_DAYLIGHT) {
                lightSourceVal = 10;
            } else if (whiteBalance == CameraParameters.WB_MODE_SHADE) {
                lightSourceVal = 11;
            }

            ValueNumber valueWB = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, whiteBalanceVal);
            exifDriver.getIfdExif().put(ExifDriver.TAG_WHITE_BALANCE, valueWB);

            ValueNumber valueLS = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, lightSourceVal);
            exifDriver.getIfdExif().put(ExifDriver.TAG_LIGHT_SOURCE, valueLS);
        }
        if (tag_spectral_sensitivity != null) {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            value.setBytes(tag_spectral_sensitivity.getBytes());
            exifDriver.getIfd0().put(ExifDriver.TAG_SPECTRAL_SENSITIVITY, value);
        }
        if (tag_version != null && !tag_version.equals("48 50 50 48")) {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            value.setBytes(tag_version.getBytes());
            exifDriver.getIfd0().put(ExifDriver.TAG_EXIF_VERSION, value);
        } else {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            byte[] version = { (byte) 48, (byte) 50, (byte) 50, (byte) 48 };
            value.setBytes(version);
            exifDriver.getIfd0().put(ExifDriver.TAG_EXIF_VERSION, value);
        }
        if (tag_metering_mode != null && !tag_metering_mode.equals("")
                && Integer.parseInt(tag_metering_mode) <= 255) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                    Integer.parseInt(tag_metering_mode));
            exifDriver.getIfdExif().put(ExifDriver.TAG_METERING_MODE, value);
            exifDriver.getIfd0().put(ExifDriver.TAG_METERING_MODE, value);
        } else {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, 0);
            exifDriver.getIfdExif().put(ExifDriver.TAG_METERING_MODE, value);
            exifDriver.getIfd0().put(ExifDriver.TAG_METERING_MODE, value);
        }

        ValueNumber xValue = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_LONG, x);
        exifDriver.getIfdExif().put(ExifDriver.TAG_IMAGE_WIDTH, xValue);

        ValueNumber yValue = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_LONG, y);
        exifDriver.getIfdExif().put(ExifDriver.TAG_IMAGE_HEIGHT, yValue);

        String dateString = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(new Date());
        if (dateString != null) {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            // Date string length is 19 bytes. But exif tag
            // specification length is 20 bytes.
            // That's why we add "empty" byte (0x00) in the end.
            byte[] bytes = dateString.getBytes();
            byte[] res = new byte[20];
            for (int ii = 0; ii < bytes.length; ii++) {
                res[ii] = bytes[ii];
            }
            res[19] = 0x00;
            value.setBytes(res);
            exifDriver.getIfd0().put(ExifDriver.TAG_DATETIME, value);
            exifDriver.getIfdExif().put(ExifDriver.TAG_DATETIME_DIGITIZED, value);
            exifDriver.getIfdExif().put(ExifDriver.TAG_DATETIME_ORIGINAL, value);
        }

        // extract mode name
        String tag_modename = getFromSharedMem("mode_name" + Long.toString(sessionID));
        if (tag_modename == null)
            tag_modename = "";
        String softwareString = getResources().getString(R.string.app_name) + ", " + tag_modename;
        ValueByteArray softwareValue = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
        softwareValue.setBytes(softwareString.getBytes());
        exifDriver.getIfd0().put(ExifDriver.TAG_SOFTWARE, softwareValue);

        if (enableExifTagOrientation) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, exif_orientation);
            exifDriver.getIfd0().put(ExifDriver.TAG_ORIENTATION, value);
        } else {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                    ExifInterface.ORIENTATION_NORMAL);
            exifDriver.getIfd0().put(ExifDriver.TAG_ORIENTATION, value);
        }

        // Save exif info to new file, and replace old file with new
        // one.
        File modifiedFile = new File(file.getAbsolutePath() + ".tmp");
        exifDriver.save(modifiedFile.getAbsolutePath());
        return modifiedFile;
    }
    return null;
}

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

public static int saveExifToInput(File file, int displayOrientation, boolean cameraMirrored, boolean saveGeo) {
    try {/*from  w  w  w.  j  a v  a2s.co m*/
        ExifInterface ei = new ExifInterface(file.getAbsolutePath());
        int exif_orientation = ExifInterface.ORIENTATION_NORMAL;
        switch (displayOrientation) {
        default:
        case 0:
            exif_orientation = ExifInterface.ORIENTATION_NORMAL;
            break;
        case 90:
            if (cameraMirrored) {
                displayOrientation = 270;
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_270;
            } else {
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_90;
            }
            break;
        case 180:
            exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
            break;
        case 270:
            if (cameraMirrored) {
                displayOrientation = 90;
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_90;
            } else {
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_270;
            }
            break;
        }
        ei.setAttribute(ExifInterface.TAG_ORIENTATION, "" + exif_orientation);

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

            if (l != null) {
                ei.setAttribute(ExifInterface.TAG_GPS_LATITUDE, GPSTagsConverter.convert(l.getLatitude()));
                ei.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF,
                        GPSTagsConverter.latitudeRef(l.getLatitude()));
                ei.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, GPSTagsConverter.convert(l.getLongitude()));
                ei.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF,
                        GPSTagsConverter.longitudeRef(l.getLongitude()));

            }
        }

        ei.saveAttributes();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return displayOrientation;
}