Example usage for android.media ExifInterface ExifInterface

List of usage examples for android.media ExifInterface ExifInterface

Introduction

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

Prototype

public ExifInterface(InputStream inputStream) throws IOException 

Source Link

Document

Reads Exif tags from the specified image input stream.

Usage

From source file:org.egov.android.view.activity.CreateComplaintActivity.java

public String compressImage(String fromfilepath, String tofilepath) {

    Bitmap scaledBitmap = null;/* ww  w  .j  a va  2  s .com*/

    BitmapFactory.Options options = new BitmapFactory.Options();

    //      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
    //      you try the use the bitmap here, you will get null.
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(fromfilepath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    //      max Height and width values of the compressed image is taken as 816x612

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    //      width and height values are set maintaining the aspect ratio of the image

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

    //      setting inSampleSize value allows to load a scaled down version of the original image

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

    //      inJustDecodeBounds set to false to load the actual bitmap
    options.inJustDecodeBounds = false;

    //      this options allow android to claim the bitmap memory if it runs low on memory
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

    try {
        //          load the bitmap from its path
        bmp = BitmapFactory.decodeFile(tofilepath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    float ratioX = actualWidth / (float) options.outWidth;
    float ratioY = actualHeight / (float) options.outHeight;
    float middleX = actualWidth / 2.0f;
    float middleY = actualHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2,
            new Paint(Paint.FILTER_BITMAP_FLAG));

    String attrLatitute = null;
    String attrLatituteRef = null;
    String attrLONGITUDE = null;
    String attrLONGITUDEREf = null;

    //      check the rotation of the image and display it properly
    ExifInterface exif;
    try {
        exif = new ExifInterface(fromfilepath);

        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
        Log.d("EXIF", "Exif: " + orientation);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 3) {
            matrix.postRotate(180);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 8) {
            matrix.postRotate(270);
            Log.d("EXIF", "Exif: " + orientation);
        }

        attrLatitute = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
        attrLatituteRef = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
        attrLONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
        attrLONGITUDEREf = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
                scaledBitmap.getHeight(), matrix, true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(tofilepath);

        //          write the compressed bitmap at the destination specified by filename.
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        ExifInterface exif2 = new ExifInterface(tofilepath);

        if (attrLatitute != null) {
            exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE, attrLatitute);
            exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, attrLONGITUDE);
        }

        if (attrLatituteRef != null) {
            exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, attrLatituteRef);
            exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, attrLONGITUDEREf);
        }
        exif2.saveAttributes();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return tofilepath;
}

From source file:mobisocial.bento.todo.ui.TodoListFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (DEBUG)//from w  w  w. ja  v  a2 s  .  c o  m
        Log.d(TAG, "requestCode: " + requestCode + ", resultCode: " + resultCode);
    if (resultCode == Activity.RESULT_OK) {
        try {
            File imageFile = null;

            if (requestCode == REQUEST_IMAGE_CAPTURE) {

                imageFile = JpgFileHelper.getTmpFile();

            } else if (requestCode == REQUEST_GALLERY) {
                Uri uri = data.getData();
                if (uri == null || uri.toString().length() == 0) {
                    return;
                }

                if (DEBUG)
                    Log.d(TAG, "data URI: " + uri.toString());

                ContentResolver cr = getActivity().getContentResolver();
                String[] columns = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
                Cursor c = cr.query(uri, columns, null, null, null);

                if (c != null && c.moveToFirst()) {
                    if (c.getString(0) != null) {
                        //regular processing for gallery files
                        imageFile = new File(c.getString(0));
                    } else {
                        final InputStream is = getActivity().getContentResolver().openInputStream(uri);
                        imageFile = JpgFileHelper.saveTmpFile(is);
                        is.close();
                    }
                } else if (uri.toString().startsWith("content://com.android.gallery3d.provider")) {
                    // motorola xoom doesn't work for contentresolver even if the image comes from picasa.
                    // So just adds the condition of startsWith...
                    // See in detail : http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/
                    uri = Uri.parse(
                            uri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
                    final InputStream is = getActivity().getContentResolver().openInputStream(uri);
                    imageFile = JpgFileHelper.saveTmpFile(is);
                    is.close();
                } else {
                    // http or https
                    HttpURLConnection http = null;
                    URL url = new URL(uri.toString());
                    http = (HttpURLConnection) url.openConnection();
                    http.setRequestMethod("GET");
                    http.connect();

                    final InputStream is = http.getInputStream();
                    imageFile = JpgFileHelper.saveTmpFile(is);
                    is.close();
                    if (http != null)
                        http.disconnect();
                }
            }

            if (imageFile.exists() && imageFile.length() > 0) {
                if (DEBUG)
                    Log.d(TAG, "imageFile exists=" + imageFile.exists() + " length=" + imageFile.length()
                            + " path=" + imageFile.getPath());

                float degrees = 0;
                try {
                    ExifInterface exif = new ExifInterface(imageFile.getPath());
                    switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL)) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degrees = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degrees = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degrees = 270;
                        break;
                    default:
                        degrees = 0;
                        break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = BitmapHelper.getResizedBitmap(imageFile, BitmapHelper.MAX_IMAGE_WIDTH,
                        BitmapHelper.MAX_IMAGE_HEIGHT, degrees);

                TodoListItem item = new TodoListItem();
                item.uuid = UUID.randomUUID().toString();
                item.title = "";
                item.description = "";
                item.bDone = false;
                item.hasImage = true;
                item.creDateMillis = System.currentTimeMillis();
                item.modDateMillis = System.currentTimeMillis();
                item.creContactId = mManager.getLocalContactId();
                item.modContactId = mManager.getLocalContactId();

                StringBuilder msg = new StringBuilder(
                        getString(R.string.feed_msg_added_photo, mManager.getLocalName()));
                String plainMsg = UIUtils.getPlainString(mManager.getBentoListItem().bento.name,
                        msg.toString());

                mManager.addTodo(item, bitmap, plainMsg);

                refreshView();

                JpgFileHelper.deleteTmpFile();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.klinker.android.twitter.activities.compose.Compose.java

private Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException {
    InputStream input = getContentResolver().openInputStream(uri);
    int reqWidth = 150;
    int reqHeight = 150;

    byte[] byteArr = new byte[0];
    byte[] buffer = new byte[1024];
    int len;// w  w w  .j a  va 2s. co  m
    int count = 0;

    try {
        while ((len = input.read(buffer)) > -1) {
            if (len != 0) {
                if (count + len > byteArr.length) {
                    byte[] newbuf = new byte[(count + len) * 2];
                    System.arraycopy(byteArr, 0, newbuf, 0, count);
                    byteArr = newbuf;
                }

                System.arraycopy(buffer, 0, byteArr, count, len);
                count += len;
            }
        }

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        Bitmap b = BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        ExifInterface exif = new ExifInterface(IOUtils.getPath(uri, context));
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        b = ImageUtils.cropSquare(b);

        return rotateBitmap(b, orientation);

    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }
}

From source file:com.daiv.android.twitter.ui.compose.Compose.java

private Bitmap getThumbnail(Uri uri) throws IOException {
    InputStream input = getContentResolver().openInputStream(uri);
    int reqWidth = 150;
    int reqHeight = 150;

    byte[] byteArr = new byte[0];
    byte[] buffer = new byte[1024];
    int len;//  w w  w .  j av a2 s. c o m
    int count = 0;

    try {
        while ((len = input.read(buffer)) > -1) {
            if (len != 0) {
                if (count + len > byteArr.length) {
                    byte[] newbuf = new byte[(count + len) * 2];
                    System.arraycopy(byteArr, 0, newbuf, 0, count);
                    byteArr = newbuf;
                }

                System.arraycopy(buffer, 0, byteArr, count, len);
                count += len;
            }
        }

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        Bitmap b = BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        ExifInterface exif = new ExifInterface(IOUtils.getPath(uri, context));
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        b = ImageUtils.cropSquare(b);

        return rotateBitmap(b, orientation);

    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }
}

From source file:com.mk4droid.IMC_Activities.Fragment_NewIssueA.java

/**
 *        Check Image Orientation  //from  w  ww  . j  a v a 2 s  .  co  m
 */
public void CheckOrient() {

    BitmapFactory.Options options = new BitmapFactory.Options(); // Resize is needed otherwize outofmemory exception
    options.inSampleSize = 6;

    //------------- read tmp file ------------------ 
    Image_BMP = BitmapFactory.decodeFile(image_path_source_temp, options); // , options

    //---------------- find exif header --------
    ExifInterface exif;
    String exifOrientation = "0"; // 0 = exif not working
    try {
        exif = new ExifInterface(image_path_source_temp);
        exifOrientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    //---------------- Resize ---------------------
    if (exifOrientation.equals("0")) {
        if (Image_BMP.getWidth() < Image_BMP.getHeight() && Image_BMP.getWidth() > 400) {
            Image_BMP = Bitmap.createScaledBitmap(Image_BMP, 400, 640, true); // <- To sent
        } else if (Image_BMP.getWidth() > Image_BMP.getHeight() && Image_BMP.getWidth() > 640) {
            Image_BMP = Bitmap.createScaledBitmap(Image_BMP, 640, 400, true); // <- To sent
        }
    } else {

        if (exifOrientation.equals("1") && Image_BMP.getWidth() > 640) { // normal

            Image_BMP = Bitmap.createScaledBitmap(Image_BMP, 640, 400, true); // <- To sent

        } else if (exifOrientation.equals("6") && Image_BMP.getWidth() > 400) { // rotated 90 degrees

            // Rotate
            Matrix matrix = new Matrix();

            int bmwidth = Image_BMP.getWidth();
            int bmheight = Image_BMP.getHeight();

            matrix.postRotate(90);

            Image_BMP = Bitmap.createBitmap(Image_BMP, 0, 0, bmwidth, bmheight, matrix, true);

            Image_BMP = Bitmap.createScaledBitmap(Image_BMP, 400, 640, true); // <- To sent
        }
    }

    DisplayMetrics metrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

    //------------ now store as jpg over the temp jpg
    File imagef = new File(image_path_source_temp);
    try {
        Image_BMP.compress(Bitmap.CompressFormat.JPEG, 95, new FileOutputStream(imagef));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*  w ww .  j  a va  2  s. c o m*/
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    Bitmap b = BitmapFactory.decodeFile(path, options);

    ExifInterface exif;
    try {
        exif = new ExifInterface(path);
    } catch (IOException e) {
        return null;
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
    Matrix matrix = new Matrix();
    if (orientation == 6)
        matrix.postRotate(90);
    else if (orientation == 3)
        matrix.postRotate(180);
    else if (orientation == 8)
        matrix.postRotate(270);

    return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
}

From source file:com.daiv.android.twitter.ui.compose.Compose.java

public Bitmap getBitmapToSend(Uri uri) throws IOException {
    InputStream input = getContentResolver().openInputStream(uri);
    int reqWidth = 750;
    int reqHeight = 750;

    byte[] byteArr = new byte[0];
    byte[] buffer = new byte[1024];
    int len;//  ww  w.j ava  2 s .c o m
    int count = 0;

    try {
        while ((len = input.read(buffer)) > -1) {
            if (len != 0) {
                if (count + len > byteArr.length) {
                    byte[] newbuf = new byte[(count + len) * 2];
                    System.arraycopy(byteArr, 0, newbuf, 0, count);
                    byteArr = newbuf;
                }

                System.arraycopy(buffer, 0, byteArr, count, len);
                count += len;
            }
        }

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        Bitmap b = BitmapFactory.decodeByteArray(byteArr, 0, count, options);

        ExifInterface exif = new ExifInterface(IOUtils.getPath(uri, context));
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        input.close();

        return rotateBitmap(b, orientation);

    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }
}

From source file:com.cloverstudio.spika.CameraCropActivity.java

protected void onPhotoTaken(String path) {

    String fileName = Uri.parse(path).getLastPathSegment();
    mFilePath = CameraCropActivity.this.getExternalCacheDir() + "/" + fileName;

    if (!path.equals(mFilePath)) {
        copy(new File(path), new File(mFilePath));
    }/*from  ww  w  . j  av  a2 s. c o  m*/

    new AsyncTask<String, Void, byte[]>() {
        boolean loadingFailed = false;

        @Override
        protected byte[] doInBackground(String... params) {
            try {

                if (params == null)
                    return null;

                File f = new File(params[0]);
                ExifInterface exif = new ExifInterface(f.getPath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                int angle = 0;

                if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                    angle = 90;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                    angle = 180;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                    angle = 270;
                }

                Matrix mat = new Matrix();
                mat.postRotate(angle);

                BitmapFactory.Options optionsMeta = new BitmapFactory.Options();
                optionsMeta.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(f.getAbsolutePath(), optionsMeta);

                BitmapFactory.Options options = new BitmapFactory.Options();

                options.inSampleSize = BitmapManagement.calculateInSampleSize(optionsMeta, 640, 640);
                options.inPurgeable = true;
                options.inInputShareable = true;
                mBitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
                mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), mat,
                        true);
                _scaleBitmap();
                return null;
            } catch (Exception ex) {
                loadingFailed = true;
                finish();
            }

            return null;
        }

        @Override
        protected void onPostExecute(byte[] result) {
            super.onPostExecute(result);

            if (null != mBitmap) {
                mImageView.setImageBitmap(mBitmap);
                mImageView.setScaleType(ScaleType.MATRIX);
                translateMatrix.setTranslate(-(mBitmap.getWidth() - crop_container_size) / 2f,
                        -(mBitmap.getHeight() - crop_container_size) / 2f);
                mImageView.setImageMatrix(translateMatrix);

                matrix = translateMatrix;

            }

        }
    }.execute(mFilePath);

}

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

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    File tempPhotoFile = new File(mTempPhotoPath);

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        GISApplication app = (GISApplication) getActivity().getApplication();
        ContentResolver contentResolver = app.getContentResolver();
        String photoFileName = getPhotoFileName();

        try {/* w w w .  j a v a  2 s.  com*/
            BitmapUtil.writeLocationToExif(tempPhotoFile, app.getCurrentLocation(), 0);
        } catch (IOException e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName
                + "/" + mObjectId + "/attach");

        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;
        try {
            attachUri = contentResolver.insert(allAttachesUri, values);

        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        if (null != attachUri) {

            try {
                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);

                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);
                FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream);
                attachOutStream.close();

                tempAttachFile.delete();

            } catch (IOException e) {
                Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }

            Log.d(TAG, attachUri.toString());

        } else {
            Log.d(TAG, "insert attach failed");
        }

        try {
            if (app.isOriginalPhotoSaving()) {
                File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName);

                if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) {
                    Toast.makeText(getActivity(), "Save original photo failed", Toast.LENGTH_LONG).show();
                }

            } else {
                tempPhotoFile.delete();
            }

            setPhotoGalleryAdapter();
            setPhotoGalleryVisibility(true);

        } catch (IOException e) {
            Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_CANCELED) {
        tempPhotoFile.delete();
    }
}

From source file:com.plusapp.pocketbiceps.app.MainActivity.java

@TargetApi(Build.VERSION_CODES.N)
@Override/*from w  ww.  j  a va2s . co m*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch (requestCode) {

    // Nach dem man ein Foto mit der Kamera aufgenommen hat wird onActivityResult aufgerufen, bei dem ueberprueft wird ob man das Bild mit Ok oder mit Abbrechen bestaetigt hat
    case 1:
        // Wenn nicht auf Abbrechen in der CameraAct. gedrueckt wurde, werden die daten gespeichert
        // und die AddActivity wird gestartet
        if (resultCode == RESULT_OK) {

            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy-HH-mm-SS");
            String dateString = formatter.format(new Date(currTime));
            //Speichert das gemachte Bild im path
            String path = IMAGE_PATH_URI + IMAGE_NAME_PREFIX + dateString + ".jpg";
            Drawable.createFromPath(path);
            Intent intent = new Intent(MainActivity.this, AddActivity.class);
            // Die currTime Variable wird in die AddActivity weitergegeben, da sie dort als Index benoetigt wird
            intent.putExtra("currTime", currTime);

            startActivity(intent);
        }
        break;

    // Bild von der Gallerie importieren
    case 2:
        super.onActivityResult(requestCode, resultCode, data);

        try {
            // Wenn das Bild ausgewaehlt wurde
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

                // Hole das Bild von data
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                String time = "";
                long originalTimeInMilli = 0;
                // Cursor holen
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                Drawable.createFromPath(imgDecodableString);

                // Hole das heutige Datum
                this.currTime = System.currentTimeMillis();

                ExifInterface exif = new ExifInterface(imgDecodableString);
                if (exif != null) {
                    time = exif.getAttribute(ExifInterface.TAG_DATETIME);
                    if (time != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
                        try {
                            Date mDate = sdf.parse(time);
                            originalTimeInMilli = mDate.getTime();
                        } catch (ParseException e) {
                            e.printStackTrace();
                            time = null;
                        }
                    }
                }

                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                if (time == null) {
                    intent.putExtra("currTime", currTime);
                } else {
                    intent.putExtra("currTime", originalTimeInMilli);
                }
                intent.putExtra("pathName", imgDecodableString);
                intent.putExtra("fromGallery", "true");

                startActivity(intent);

            } else {
                Toast.makeText(this, R.string.no_pic_chosen, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
        }
        break;

    }

}