Example usage for android.media ExifInterface setAttribute

List of usage examples for android.media ExifInterface setAttribute

Introduction

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

Prototype

public void setAttribute(String tag, String value) 

Source Link

Document

Set the value of the specified tag.

Usage

From source file:Main.java

public static boolean copyExifRotation(File sourceFile, File destFile) {
    if (sourceFile == null || destFile == null)
        return false;
    try {//  w  w w  .  j  av  a  2 s .c o m
        ExifInterface exifSource = new ExifInterface(sourceFile.getAbsolutePath());
        ExifInterface exifDest = new ExifInterface(destFile.getAbsolutePath());
        exifDest.setAttribute(ExifInterface.TAG_ORIENTATION,
                exifSource.getAttribute(ExifInterface.TAG_ORIENTATION));
        exifDest.saveAttributes();
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:Main.java

public static void compressFileIfNeeded(String filePath) {
    File f = new File(filePath);

    Bitmap bitmap;/*from  w w w .ja va  2 s  . c o  m*/
    bitmap = BitmapFactory.decodeFile(filePath);
    int MAX_IMAGE_SIZE = 1000 * 1024;
    int streamLength = (int) f.length();
    if (streamLength > MAX_IMAGE_SIZE) {
        int compressQuality = 105;
        ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
        while (streamLength >= MAX_IMAGE_SIZE && compressQuality > 5) {
            try {
                bmpStream.flush();//to avoid out of memory error
                bmpStream.reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
            compressQuality -= 5;
            bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
            byte[] bmpPicByteArray = bmpStream.toByteArray();
            streamLength = bmpPicByteArray.length;
            Log.d("test upload", "Quality: " + compressQuality);
            Log.d("test upload", "Size: " + streamLength);
        }

        FileOutputStream fo;

        try {
            f.delete();
            f = new File(filePath);
            fo = new FileOutputStream(f);
            fo.write(bmpStream.toByteArray());
            fo.flush();
            fo.close();
            ExifInterface exif = new ExifInterface(f.getAbsolutePath());
            exif.setAttribute(ExifInterface.TAG_ORIENTATION, "6");
            exif.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void removeExif(String path) {
    if (!TextUtils.isEmpty(path)) {
        return;//  w w  w.j a v  a2  s. c om
    }
    ExifInterface exifInterface;
    try {
        exifInterface = new ExifInterface(path);
    } catch (IOException ignore) {
        return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        exifInterface.setAttribute(ExifInterface.TAG_ARTIST, "");
        exifInterface.setAttribute(ExifInterface.TAG_RESOLUTION_UNIT, "0");
        exifInterface.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, "");
        exifInterface.setAttribute(ExifInterface.TAG_MAKER_NOTE, "0");
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        exifInterface.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, "");
    }
    exifInterface.setAttribute(ExifInterface.TAG_MAKE, "");
    exifInterface.setAttribute(ExifInterface.TAG_MODEL, "");
    exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "0");

    exifInterface.setAttribute(ExifInterface.TAG_DATETIME, "");
    exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, "");
    exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, "");

    exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, "");

}

From source file:Main.java

/**
 * Store the exif attributes in the passed image file using the TAGS stored in the passed bundle
 *
 * @param filepath/*from   w w w  . j  av a 2s.  c  o m*/
 * @param bundle
 * @return true if success
 */
public static boolean saveAttributes(final String filepath, Bundle bundle) {
    ExifInterface exif;
    try {
        exif = new ExifInterface(filepath);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    for (String tag : EXIF_TAGS) {
        if (bundle.containsKey(tag)) {
            exif.setAttribute(tag, bundle.getString(tag));
        }
    }
    try {
        exif.saveAttributes();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:Main.java

public static void copyExifData(File srcImgFile, File dstImgFile) throws IOException {
    ExifInterface srcExif = new ExifInterface(srcImgFile.getCanonicalPath());
    ExifInterface dstExif = new ExifInterface(dstImgFile.getCanonicalPath());

    int buildSDKVersion = Build.VERSION.SDK_INT;

    // From API 11
    if (buildSDKVersion >= Build.VERSION_CODES.HONEYCOMB) {
        if (srcExif.getAttribute(ExifInterface.TAG_APERTURE) != null) {
            dstExif.setAttribute(ExifInterface.TAG_APERTURE, srcExif.getAttribute(ExifInterface.TAG_APERTURE));
        }/*from  w  ww .  ja va 2  s . c  o m*/
        if (srcExif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME) != null) {
            dstExif.setAttribute(ExifInterface.TAG_EXPOSURE_TIME,
                    srcExif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME));
        }
        if (srcExif.getAttribute(ExifInterface.TAG_ISO) != null) {
            dstExif.setAttribute(ExifInterface.TAG_ISO, srcExif.getAttribute(ExifInterface.TAG_ISO));
        }
    }

    // From API 9
    if (buildSDKVersion >= Build.VERSION_CODES.GINGERBREAD) {
        if (srcExif.getAttribute(ExifInterface.TAG_GPS_ALTITUDE) != null) {
            dstExif.setAttribute(ExifInterface.TAG_GPS_ALTITUDE,
                    srcExif.getAttribute(ExifInterface.TAG_GPS_ALTITUDE));
        }
        if (srcExif.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF) != null) {
            dstExif.setAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF,
                    srcExif.getAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF));
        }
    }

    // From API 8
    if (buildSDKVersion >= Build.VERSION_CODES.FROYO) {
        if (srcExif.getAttribute(ExifInterface.TAG_FOCAL_LENGTH) != null) {
            dstExif.setAttribute(ExifInterface.TAG_FOCAL_LENGTH,
                    srcExif.getAttribute(ExifInterface.TAG_FOCAL_LENGTH));
        }
        if (srcExif.getAttribute(ExifInterface.TAG_GPS_DATESTAMP) != null) {
            dstExif.setAttribute(ExifInterface.TAG_GPS_DATESTAMP,
                    srcExif.getAttribute(ExifInterface.TAG_GPS_DATESTAMP));
        }
        if (srcExif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD) != null) {
            dstExif.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD,
                    srcExif.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD));
        }
        if (srcExif.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP) != null) {
            dstExif.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP,
                    srcExif.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP));
        }
    }

    if (srcExif.getAttribute(ExifInterface.TAG_DATETIME) != null) {
        dstExif.setAttribute(ExifInterface.TAG_DATETIME, srcExif.getAttribute(ExifInterface.TAG_DATETIME));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_FLASH) != null) {
        dstExif.setAttribute(ExifInterface.TAG_FLASH, srcExif.getAttribute(ExifInterface.TAG_FLASH));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) != null) {
        dstExif.setAttribute(ExifInterface.TAG_GPS_LATITUDE,
                srcExif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF) != null) {
        dstExif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF,
                srcExif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) != null) {
        dstExif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE,
                srcExif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF) != null) {
        dstExif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF,
                srcExif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH) != null) {
        dstExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH,
                srcExif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH) != null) {
        dstExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH,
                srcExif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_MAKE) != null) {
        dstExif.setAttribute(ExifInterface.TAG_MAKE, srcExif.getAttribute(ExifInterface.TAG_MAKE));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_MODEL) != null) {
        dstExif.setAttribute(ExifInterface.TAG_MODEL, srcExif.getAttribute(ExifInterface.TAG_MODEL));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_ORIENTATION) != null) {
        dstExif.setAttribute(ExifInterface.TAG_ORIENTATION,
                srcExif.getAttribute(ExifInterface.TAG_ORIENTATION));
    }
    if (srcExif.getAttribute(ExifInterface.TAG_WHITE_BALANCE) != null) {
        dstExif.setAttribute(ExifInterface.TAG_WHITE_BALANCE,
                srcExif.getAttribute(ExifInterface.TAG_WHITE_BALANCE));
    }

    dstExif.saveAttributes();
}

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 . ja v  a 2 s. c o m*/
            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:org.egov.android.view.activity.CreateComplaintActivity.java

public String compressImage(String fromfilepath, String tofilepath) {

    Bitmap scaledBitmap = null;//  w w  w .ja  v  a  2  s.  co m

    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: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;//from  w w  w .  ja v a2 s.c  o m
    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:com.almalence.opencam.PluginManagerBase.java

public static int saveExifToInput(File file, int displayOrientation, boolean cameraMirrored, boolean saveGeo) {
    try {/* w  w w . ja  va2s.  c o  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;
}

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  w w  . ja  v  a 2s  .  c  o m
        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;
}